Executing multiple catch blocks in C#

Today I saw a discussion on FB questioning "Can multiple catch blocks be executed?". Many guys were confused in answering that question, few of them answered "YES". I am writing this post to support my answer.
Here is a program in support with this answer.
using System;
using System.Linq;
 
namespace ConsoleApplication1
{
 
    //Run this program and type 0 (that is numeric) and 'a' (that is char) on the console to check both catch blocks in action.
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int numerator = 10;
                int denominator = GetText();
                int result = numerator / denominator;
            }
            catch (DivideByZeroException ex1)
            {
                string msg = ex1.Message.ToString();
                Console.WriteLine(msg + " I'm from 1st catch block");
            }
            catch (Exception ex2)
            {
                string msg = ex2.Message.ToString();
                Console.WriteLine(msg + " I'm from 2nd catch block");
            }
            finally
            {
                //Console.WriteLine("In finally block.");
            }
            Console.ReadKey();
        }
 
        private static int GetText()
        {
            string x = Console.ReadLine();
            return Convert.ToInt32(x);
        }
    }
}

The output of this program is: "Attempted to divide by zero".
So, yes it is possible to execute multiple catch blocks, just keep all catch blocks in order means put your super class exception (that is "Exception ex2" in above code) at the bottom.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples