Friday, January 10, 2014

examples for using try-catch-finally block in asp.net

In this post i will show how to use try-catch-finally block in asp.net.
try block has to be used accompanied my catch block or finally block or both.

1. Using  try-catch-finally block ( Finally block will be executed whether there is a exception or not )

Example :
             try
            {
                int a = 10;
                int b = 0;
                int z = a / b;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
              
            }
            finally
            {
                Console.WriteLine("Finally Block");
                Console.ReadLine();
            }



2. Using try-finally block (No Exception handled here as the catch block is removed)

Example :

          try
            {
                int a = 10;
                int b = 10;
                int z = a / b;
            }
           
            finally
            {
                Console.WriteLine("Finally Block");
                Console.ReadLine();
            }



3.  Using try-catch block

Example :

             try
            {
                int a = 10;
                int b = 0;
                int z = a / b;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }