Multiple Catch Blocks in C#: should read

In this article we’ll discuss how to use multiple catch Blocks in C# program with the help of some example. In C#, you can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.

C# does not allow you to use multiple catch block for the same type of Exception

If you use multiple catch blocks in C# for the same type of exception, then it will give you a compile-time error and a catch block is always preceded by the try block i.e., catch block can never be used standalone without try.

In general, the catch block is executed within the order in which they are written in the program. If the given type of exception is matched with the first catch block, then first catch block executes and the remaining of the catch blocks are ignored. And if the starting catch block is not suitable for the exception type, then compiler search for the next catch block until it gets desired CATCH block.

Try with multiple catch blocks in C#: Syntax

Multiple Catch Blocks in C#

What must take care while using multiple catch blocks in C#? 

We know that Exception class is main abstract class, all other exception classes can be inherited from it. So, the point which need to take care is Exception class must be in last catch block not in other catch blocks, else it will catch all the errors in its block and rest of remaining CATCH blocks will never be executed.

Code sample:

class ExceptionTest
{
    static void Main(string[] args)
    {
        int num1=1;
        int num2=0;
        int num3=0;
        
        try
        {
          // we’ll try to divide 1 by Zero to get error.  
            num3 = num1 / num2;
        }
        catch (DivideByZeroException exp)
        {
            Console.WriteLine(exp.Message);
        }
        catch (FormatException fe)
        {
            Console.WriteLine("Exception: Invalid format");
        }
        catch (Exception ex)
        {
            Console.WriteLine("exception generated="+ ex.Message);
        }
    }
}

An above example we see how to work with multiple Catch blocks now in below example we’ll how to add switch case pattern under one CATCH.

Single Catch Blocks with Switch Pattern

To separately manage all exceptions in one catch block, we can utilize the switch pattern syntax too. Let’s create a sample as below:   

try
    {
        Int  testValue = 1/0;
        
    }
    catch (Exception ex)
    {
        switch (ex)
        {
            case FormatException:
                Console.WriteLine("Format Exception!");
                break;
            case DivideByZeroException:
                Console.WriteLine("Divide By Zero Exception!");
                break;
            case OverflowException:
                Console.WriteLine("Overflow Exception!");
                break;
        }
    }

We catch all the exceptions in a single CATCH block and separate them using a switch-case pattern. Above mentioned, switch (ex) can recognize the type of the “ex” variable and compare it with each case. On the other hand, we can also use the if-else pattern instead of a switch-case model but considering performance switch must be used for better performance.

Single Catch Blocks with or operator

We can use one CATCH block and instead of switch case we can put II i.e. OR operator in between different type of exceptions and specified type of errors will log under that block. For more detail, please check below code sample:

Multiple Catch Blocks in C#

Multiple Catch Blocks vs Single Catch Block

Once the application throws the exception the question is, do multiple catch blocks have better performance or a single catch block? So, after throwing an exception, the try-catch should have a switching pattern for delivering the exception to the first best case or we can also use main abstract exception class which is Exception class

 On the other hand, when we use multiple catch blocks, the compiler defines the switching model automatically. But if we write a single catch block, we should specify that switching pattern and while implementing it manually developer must use Switch case rather than if- else for the better performance.

In this article, we’ve learned how to catch multiple exceptions using different approaches. First is using multiple catch blocks and second is using switch case in single catch block. I believe after reading this article you’ll be able to use this in your daily development practices. You can check more on Microsoft Learn.

Are you willing to check more on C# then please visit HERE

Leave a Reply

Your email address will not be published. Required fields are marked *