#870 – Where Execution Continues when an Exception Is Caught

When an exception is thrown that you catch in a catch block, the code in the catch block will execute.  Once all of the code in the catch block executes, execution will continue with the first line following the try-catch statement.  (Assuming that your catch block does not itself throw an exception).

            try
            {
                DoSomething();
                Console.WriteLine("In try block, before call that throws exception");
                DoSomethingThatThrowsAnException();
                Console.WriteLine("In try block, after call that throws exception");
                DoSomethingElse();
            }
            catch (FileNotFoundException noFileExc)
            {
                Console.WriteLine("FileNotFoundException");
            }
            catch (ArgumentOutOfRangeException argExc)
            {
                Console.WriteLine("ArgumentOutOfRangeException");
            }
            catch (Exception exc)
            {
                Console.WriteLine("Some other Exception");
            }

            Console.WriteLine("Now I'm continuing after the try-catch statement");

When this code runs, the statements in the try block begin executing.  The second method that we call results an exception, which is caught in the ArgumentOutOfRangeException catch block.  Once that block finishes executing, we continue with the code after the last catch block.

870-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #870 – Where Execution Continues when an Exception Is Caught

  1. Kirby Q. Glover says:

    This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?

    • Sean says:

      Kirby,

      No, if a handler for one type of exception itself throws an exception, it would not be caught by one of the other handlers, even if the exception type matches. Only code that executes within the context of the try block is protected by the associated handlers.

      Sean

Leave a comment