Multiple Catch Blocks and Finally Block in C#

Multiple Catch Blocks and Finally Block in C# with Examples

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 as well as finally block in C# 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#?

It is possible in C#, to write multiple catch blocks for a given try block. 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 proceed and see an example of how to implement Multiple Catch Blocks in C#.

Example: Implementing Multiple Catch Blocks in C#.

Let us see an example and understand how to implement multiple catch blocks for a given try block in C# and also understand the execution flow. Please have a look at the following example. As you can see, here, we created two catch blocks for the given try block. The first catch block taking the DivideByZeroException class as input parameter and the second catch block taking the FormatException class as the input parameter.

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 above application and entered 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 the first catch block Exception can handle all the exceptions and does not make any sense to write the further catch blocks as they are never going to be executed. 

Invalid Way to Implement Multiple Catch blocks in C#

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

Yes, it is possible. We can catch all exceptions with a single catch block with the parameter “Exception”. The Exception class is the superclass of all Exception classes and hence it can handle all types of exceptions thrown in the try block. 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 as the last catch block even though we are writing multiple catch blocks. It acts as a backup catch block. Following is the syntax to do the same.

How to Implement Multiple Catch Blocks in C#

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 messages 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. Following is the syntax to use finally block in C#,

Finally Block in C#

As you can see, in two ways we can write the finally block in C#. They are as follows:

  1. 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.
  2. Try and Finally: In this case, abnormal termination will not stop when a runtime error occurs because exceptions are not handled but even if an abnormal termination occurs, the finally blocks get executed.
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 write it in the finally block which will be always executed irrespective of the exception raised or not raised.

Example: Use of finally block in C#.

Let us see an example to understand the use of finally block in C#. In the below example, for the given try block, we have written two catch blocks and after the second catch block, we have written the finally block. The statements present inside the catch block are going to be executed irrespective of exception occurred or not, irrespective of the exception is handled or not. That means if we place something in the finally block, then those statements are definitely going to be executed.

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();
        }
    }
}
Output:

Multiple Catch Blocks and Finally Block in C# with Examples

In how many ways we can use try-catch and finally block in C#?

We can use try-catch-finally in three different ways. They are as follows:

  1. Try and Catch: In this case, the exception will be handled and stop the abnormal termination.
  2. 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.
  3. 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 am going to discuss how to create a Custom Exception in C# with Examples. Here, in this article, I try to explain how to implements Multiple Catch Blocks in C# with Examples as well as we also discuss the need and use of finally block in C#. I hope you understood this as well as enjoy this Multiple Catch Blocks and Finally in C# article. 

2 thoughts on “Multiple Catch Blocks and Finally Block in C#”

Leave a Reply

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