Varun Sharma
Varun Sharma

Reputation: 2758

Why is this C# code crashing the process?

static void Main(string[] args)
        {
            try
            {
                var intValue = "test";
                var test = Convert.ToInt32(intValue);
            }
            catch (FormatException)
            {
                Console.WriteLine("format exception");
                throw;
            }
            catch (Exception)
            {

            }
            finally
            {
                Console.WriteLine("finally");
            }
        }

According to me, during conversion from string to int, a FormatException is thrown. Now inside the catch block, we are re throwing the original exception. Why is this not caught in the generic exception catch block? If I put try/catch around the throw then application doesn't crashes.

Upvotes: 1

Views: 56

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Why is this not caught in the generic exception catch block?

Because the generic exception block catches exceptions that are thrown only within the try block and doesn't catch exceptions thrown from catch blocks.

So if you intend to throw an exception from the catch block and you want to handle it, you will need to wrap the calling code in yet another try/catch.

Upvotes: 5

Related Questions