Multiple Catch Blocks in C#

Multiple Catch Blocks in C# to handle Different Types of Exception

In this article, I am going to discuss how to implement multiple catch blocks in C# to handle different types of exceptions for a single try block with examples. Please read our previous article before proceeding to this article where we discussed the basics of Exception Handling in C# with examples. As part of this article, I am going to discuss the following pointers.

  1. How to implement multiple catch blocks in C#?
  2. Is it possible to catch all exceptions using a single catch block?
  3. When should we write multiple catch blocks in C# for a single try block?
  4. What is finally block in C#?
  5. Why do we need the finally block in the real-time project?
  6. In how many ways we can use try-catch and finally block in C#?
How to Implement multiple catch blocks in C#?

When we implement multiple catch blocks in C#, then at any given point of time only one catch block going to be executed and other catch blocks will be ignored. With this keep in mind, let us understand how to implement multiple catch blocks in C# with an example.

Example1: Program to show how to implement multiple catch blocks in C#.
namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c;
            Console.WriteLine("ENTER ANY TWO NUBERS");
            try
            {
                a = int.Parse(Console.ReadLine());
                b = int.Parse(Console.ReadLine());
                c = a / b;
                Console.WriteLine("C VALUE = " + c);
            }
            catch (DivideByZeroException dbze)
            {
                Console.WriteLine("second number should not be zero");
            }
            catch (FormatException fe)
            {
                Console.WriteLine("enter only integer numbers");
            }
            Console.ReadKey();
        }
    }
}

Run the application and entered the values like 10, 0. It will give you the below output

Multiple Catch Blocks in C#

Again run the application and entered the values as 10 and abc. It will give you the below output

Multiple Catch Blocks in C#

Whenever we implement multiple catch blocks in C#, then it is not possible to write the catch blocks in the following manner, it raises to compilation error because first catch block Exception can handle all the exceptions.

Invalid Way to Implement Multiple Catch blocks in C#

Is it possible to catch all exceptions using a single catch block?

Yes, it is possible. We can catch all exceptions with a single catch block with parameter “Exception”. We need to use this catch block only for stopping the abnormal termination irrespective of the exceptions thrown from its corresponding try block.

It is always recommended to write a catch block with the exception parameter even though we are writing multiple catch blocks. It acts as a backup catch block.

When should we write multiple catch blocks in C# for a single try block?

We need to write multiple catch blocks in C# for a single try block because of the following reasons

  1. To print message specific to an exception or
  2. To execute some logic specific to an exception
The Finally block in C#

The keyword finally establishes a block that definitely executes statements placed in it irrespective of whether the exception has occurred or not, irrespective of whether the exception is handled or not in the catch block.

That means in the simple word we can say that the statements which are placed in the finally block are always executed irrespective of the way the control is coming out from the try block either by completing normally or throwing the exception by catching or not catching.

Why do we need the finally block in the real-time project?

As per the industry coding standard, within the “finally” block we need to write the resource releasing logic or clean up the code. Resource releasing logic means un-referencing objects that are created in the try block. Since the statements written in the try and catch block are not guaranteed to be executed we must place them in finally block.

For example, if we want to close ADO.NET objects such as Connection object, Command object, etc. we must call the close() method in both the try as well as in the catch block to guarantee its execution.

Instead of placing the same close() method call statements in multiple places if we can write it in the finally block which will be always executed irrespective of the exception raised or not raised.

Example2: Program to show the use of finally block.
namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c;
            Console.WriteLine("ENTER ANY TWO NUBERS");
            try
            {
                a = int.Parse(Console.ReadLine());
                b = int.Parse(Console.ReadLine());
                c = a / b;
                Console.WriteLine("C VALUE = " + c);
            }
            catch (DivideByZeroException dbe)
            {
                Console.WriteLine("2nd number should not be zero");
            }
            catch (FormatException fe)
            {
                Console.WriteLine("enter only integer number");
            }
            finally
            {
                Console.WriteLine("hello this is finally block");
            }
            Console.ReadKey();
        }
    }
}
In how many ways we can use try-catch and finally block in C#?

We can use in three different combinations

Try and catch: In this case, the exception will be handled and stop the abnormal termination.

Try, catch and finally: In this case, the exception will be handled and stopping the abnormal termination along with the statements that are placed within the “finally” block gets executed at any cost.

Try and finally: In this case, abnormal will not stop when a runtime error occurs because exceptions are not handled but even if an abnormal termination occurs also finally blocks get executed.

In the next article, I will discuss how to create a Custom Exception in C# with an example. Here, in this article, I try to explain how to implements Multiple Catch Blocks in C# step by step with some examples. I hope you understood this as well as enjoy this article. 

1 thought on “Multiple Catch Blocks in C#”

Leave a Reply

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