Multiple try-catch blocks in C#


In this article we are going to discuss Multiple try-catch Exception Handling in C#. There are many blogs, articles are available on the internet regarding Multiple try-catch 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 Multiple try-catch Exception Handling use in C#.

Using Multiple try-catch blocks

Multiple catch blocks are used when we are not sure about the exception type that may be generated, so we write different blocks to tackle any type of exception that is encountered. The finally block is the part of the code that has to be executed irrespective of if the exception was generated or not.

All the exception classes in C# are derived from System.Exception class. Let's see the list of C# common exception classes.

ExceptionDescription
System.DivideByZeroExceptionhandles the error generated by dividing a number with zero.
System.NullReferenceExceptionhandles the error generated by referencing the null object.
System.InvalidCastExceptionhandles the error generated by invalid typecasting.
System.IO.IOExceptionhandles the Input Output errors.
System.FieldAccessExceptionhandles the error generated by invalid private or protected field access.

Example

using System;
class Program
{
    static void Main()
    {
        try
        {
            int a = 10;
            int b = 0;
            int x = a / b;
        }
        // Catch block for invalid array access
        catch (IndexOutOfRangeException e)
        {

            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }

        // Catch block for attempt to divide by zero
        catch (DivideByZeroException e)
        {

            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }

        // Catch block for value being out of range
        catch (ArgumentOutOfRangeException e)
        {

            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }
        catch (Exception e) 
        { 
            Console.WriteLine(e); 
        }
        finally 
        { 
            Console.WriteLine("The 'try catch' is finished.Finally block is executed"); 
        }
        Console.ReadKey();
    }
}

Output

Exception Handling in C#
Next