ITORIAN    

  public string Welcome() {

      return "Abhimanyu's Thoughts";

  }

My First E-Book
Quick Report
Yearly Posts:
   i) Oct-Nov 2010: 12
   ii) In 2011: 380
   iii) In 2012: 32

You can find my articles and blogs on:
   i) itorian.com
   ii) c-sharpcorner.com
   iii) dotnetfunda.com
   iv) codeproject.com

Greatest Hits
People I Follow
Disclaimer
This is my personal website and the opinions I have expressed here is my own. For any accuracy I recommend to visit official websites like MSDN for Microsoft. I developed this website to share my technical skills.

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".
Abhimanyu Kumar Vatsa

IT Faculty || I blog on Microsoft Technologies || Mindcracker MVP || Founder of ITORIAN.COM
   
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.

MSDN Reference: http://msdn.microsoft.com/en-us/library/fk6t46tz.aspx


Happy Coding !!



Join us on Facebook. Join us on Twitter.

   



Approved Comments

No any comment found.