Feb 20, 2014

C# - throwing exceptions in catch block ?

Tricky question from job interview.

Will in given code finally be executed ?

string t = "x";
            try
            {
                try
                {
                    int i = int.Parse(t);
                    Console.WriteLine(i);
                }
                catch (FormatException e)
                {
                    Console.WriteLine(e.Message);
                    throw new ApplicationException("new exception...");
                }
                finally
                {
                    Console.WriteLine("finally");
                }
            }
            catch (Exception)
            {
                Console.WriteLine("handled exception...");
            }
            Console.ReadLine();

Yes it will but ONLY if new exception from catch block is handled in outer try block.

Result:

FormatException
Finally
Handled exception


In this case when outer try block is missing finally will not execute:

string t = "x";

                try
                {
                    int i = int.Parse(t);
                    Console.WriteLine(i);
                }
                catch (FormatException e)
                {
                    Console.WriteLine(e.Message);
                    throw new ApplicationException("new exception...");
                }
                finally
                {
                    Console.WriteLine("finally");
                }
            Console.ReadLine();


To conclude be very careful with code you write in your catch block.
It should not employ any kind of complexity that mighty throw exception!

No comments:

Post a Comment