Saturday, November 21, 2009

Order of execution of Catch statements

  • System.Exception is the base class for Exceptions
  • System.Exception should be the last catch block.
  • Catch block for all the child exceptions should be declared before System.Exception. Compiler throws exception if the order is not following.

  •  Sample (WRONG)

            try
            {
                int c= 10/0;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception block:" + ex.Message);
            }
            catch (DivideByZeroException dex)
            {
                Console.WriteLine("DivideByZeroException block:" + dex.Message);
            }
COMPILE ERROR: A previous catch clause already catches all exceptions of this or of a super type ('System.Exception')

  • Sample (CORRECT)
             try
            {
                int c= 10/0;
            }
            catch (DivideByZeroException dex)
            {
                Console.WriteLine("DivideByZeroException block:" + dex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception block:" + ex.Message);
            }


Eg : Another Sample