Monday, March 14, 2016

Nested try catch finally...

Google around and no one can say "NO" to this. Yes definitely we can have nested try catch finally. This is used in real time when we are not sure if finally will throw some exceptions. Below example is clearly illustrating the use of nested blocks.

Note: Below code is in C#


using System;

namespace TryCatchTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            int b = i;
            try
            {
                try
                {
                    Console.WriteLine(i);
                    Console.WriteLine(b++);
                }
                catch (Exception)
                {
                    Console.WriteLine("inner catch");
                }
                finally
                {
                    Console.WriteLine(b / i);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Outer Catch");
            }
            finally
            {
                Console.WriteLine("Outer Finally");
                Console.ReadLine();
            }
        }
    }
}

Output: 

0
0
Outer Catch
Outer Finally
_________________________________________________________________________________

In this example, when the inner finally breaks (divide by zero) it is handled by outer catch. We specifically use nested try catch if we have to write the separate exception logic for separate business functionality in same class.

Please comment if you have any queries on this. Happy to learn happy to help. :)
   

3 comments:

  1. What if outer finally breaks and throws unhandled exception.

    ReplyDelete
  2. Nice question. In the application cycle of global.asax we can handle the application level exception in void Application_Error(object sender, EventArgs e) and redirect it to the exception page to give a user more interactive and meaning full error message. The same logic can be implemented in web.config if the scope is limited. You have to set the CustomErrors mode = "On", defaultRedirect = "yourExceptionPage.aspx". You can also check with statusCode as; error statusCode="404" redirect="Http404ErrorPage.aspx"





    ReplyDelete