C# exception handling with multiple catch blocks

Here, in this instructional exercise, we will find out about the special case taking care of with numerous catch blocks in C# with examples and talking about the different exemptions too.

In a C# program, we can utilize different catch blocks to deal with the various special cases, on the grounds that occasionally it is additionally required to deal with numerous exemptions of a coding area and clear a coding segment can produce numerous exemptions.

Consider the beneath example,

Here, we are utilizing two catch blocks, one is utilizing to get “DivideByZeroException” which will happen when any number will be partitioned by zero and second is utilizing to get some other special cases as we have talked about in past instructional exercise (C# exemption taking care of) that “Special case” class is a superclass and can be utilized to deal with all sort of special cases.

using System;

class Program
{
    static void Main()
    {
        int number1 = 20;
        int number2 = 0;
        int result  = 0;

        try
        {
            result = number1 / number2;
            Console.WriteLine("Result : " + result);
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine(e.Message);
        }
        catch (Exception)
        {
            Console.WriteLine("Exception Occured");
        }
        
    }
}

Output:

C# exception handling with multiple catch blocks

Getting special cases without utilizing exemption classes:

In the event that we don’t think about the particular class that ought to be utilized to get the specific exemption, at that point we can likewise deal with/get the exemption by utilizing the “get” watchword as it were. There is no compelling reason to utilize the class name, consider the underneath program in which we are not indicating any exemption class.

using System;

class Program
{
    static void Main()
    {
       
        int result  = 0;
        int num = 0;

        try
        {
            result = 500 / num;
            Console.WriteLine("This line will not execute");
        }
        catch 
        {
            Console.WriteLine("Exception occurred in try block");
        }
    }
}

Output:

Exception occurred in try block

Leave a Comment

error: Alert: Content is protected!!