This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Custom Exception in C#


In this article we are going to discuss Custom Exception Handling in C#. There are many blogs, articles are available on the internet regarding Custom Exception Handling but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Custom Exception Handling use in C#.

Custom Exceptions(User-Defined Exceptions) Using Throw

C# allows us to create user-defined or custom exception. It is used to make the meaningful exception. You can create custom exceptions by inheriting from the Exception class.

You can create custom exceptions by inheriting from the Exception class.


using System;
public class MyCustomException : Exception
{
    public MyCustomException() { }

    public MyCustomException(string message): base(message) 
    { 
    }
}
class Program
{
    static void Main()
    {
        try
        {
            int a = 10;
            int b = 0;
            if (a != b)
            {
                throw new MyCustomException("This is a custom exception.");
            }
        }
        catch (MyCustomException e) 
        { 
            Console.WriteLine(e.Message); 
        }
        finally 
        { 
            Console.WriteLine("The 'try catch' is finished. Finally block is executed"); 
        }
        Console.ReadKey();
    }
}

Output

Exception Handling in C#
Next