Monday 20 August 2018

C#: Custom Exceptions

You can create a custom exception by inheriting Exception class. Usually custom Exception classes overrides the required constructors of base class.

Example
   class MyException : Exception
    {
        /* Default constructor */
        public MyException() : base()
        {

        }

        /* Exception provide useful message */
        public MyException(String message) : base(message){

        }

        /* Constructor used to provide support for inner exception */
        public MyException(String message, Exception e) : base(message, e)
        {

        }

    }

Following is the complete working application.

Program.cs

using System;

class Program
{
    class MyException : Exception
    {
        /* Default constructor */
        public MyException() : base()
        {

        }

        /* Exception provide useful message */
        public MyException(String message) : base(message){

        }

        /* Constructor used to provide support for inner exception */
        public MyException(String message, Exception e) : base(message, e)
        {

        }

    }

    static void Main(string[] args)
    {
        try
        {
            throw new MyException("My Custom Exception : Sleep at work");
        }catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }

    }
}


Output
My Custom Exception : Sleep at work



Previous                                                 Next                                                 Home

No comments:

Post a Comment