#865 – A catch Block Specifies the Type of Exception to Catch

In most cases, a catch block will specify the type of exception to intercept and catch.  Any exception occurring in the associated try block whose type matches the type indicated in the catch block will be caught.  Exceptions whose type is derived from the specified exception type will also be caught.

In the example below, we catch only exceptions of type FileNotFoundException, or of types that derive from this type. Other exception types will not be caught and will continue to bubble up the call stack.

            try
            {
                DoSomething();
                AskUserForFilename();
                DoSomethingElse();
            }
            catch (FileNotFoundException fnfExc)
            {
                Console.WriteLine(string.Format("Hey, we can't find file {0}!", fnfExc.FileName));
            }

#864 – An Example of a finally Block with No catch Block

When an exception occurs while executing code in a try block that has an associated finally block, the code in the finally block will execute before the exception bubbles up the call stack.

Below is an example.  MethodA calls MethodB, which in turn calls MethodC.  MethodC throws an exception.  When this happens, the code in MethodB’s try block is interrupted and the code in the finally block is executed.  The exception then bubbles up the call stack, where it is then caught by the catch block in MethodA.

        private static void MethodA()
        {
            try
            {
                MethodB();
                Console.WriteLine("After MethodB call");
            }
            catch (Exception xx)
            {
                Console.WriteLine("Exception caught in MethodA!");
            }

            Console.WriteLine("Finishing up MethodA");
        }

        private static void MethodB()
        {
            try
            {
                Console.WriteLine("Before MethodC() call");
                MethodC();
                Console.WriteLine("After MethodC() call");
            }
            finally
            {
                Console.WriteLine("MethodB() finally block");
            }

            Console.WriteLine("Finishing up MethodB()");
        }

        private static void MethodC()
        {
            throw new Exception("Uh-oh");
        }

864-001

#862 – Options for Including catch and finally Blocks

When you define a try block using the try keyword, you must also do one of the following:

  • Include one or more catch blocks after the try block
  • Include a finally block after the try block
  • Include one or more catch blocks after the try block, followed by a finally block

Whether you include a catch block, a finally block, or both, depends on what you want to accomplish:

  • Include catch blocks to intercept and act upon exceptions that got thrown as a result of executing the code in the try block.
  • Include a finally block if there are things that need to happen (like releasing resources), regardless of whether or not an exception occurs.
  • Include both catch and finally blocks if both statements above are true.

#861 – A finally Block Always Executes

When you use a try block, you’re defining a block of code for which you can catch an exception, using a catch block.  You can also include a finally block, which dictates a block of code that will execute whether or not an exception occurs.

Suppose that you have the following code:

                try
                {
                    Console.WriteLine("BEFORE the call");
                    SomeMethod();
                    Console.WriteLine("AFTER the call");
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Exception caught in catch block");
                }
                finally
                {
                    Console.WriteLine("Code in finally block executing");
                }

If an exception does not occur, all of the code in the try block will execute, followed by all of the code in the finally block.

861-001

 

If the SomeMethod method throws an exception, the code in the try block after the call to SomeMethod will not execute.  Instead, the code in the catch block will execute, followed by the code in the finally block.

861-002

#860 – Exceptions Bubble up the Call Stack

When you define a try/catch block, the handler defined in the catch block will catch exceptions that originate directly from the code in the try block.  But the handler will also catch exceptions that originate in methods called from the code in the try block, or from code that those methods call.  In short, a catch block will catch any exceptions thrown by code that executes as a result of executing the block of code in the try block.  (Assuming that the exception is not caught elsewhere).

In the example below, code within a try block calls SomeMethod, which calls AnotherMethod.  AnotherMethod then calls YetAnother.  If an exception is thrown from the YetAnother method, the exception will bubble up the call stack until an exception handler is found.  In this the handler associated with the try block around the SomeMethod call will catch the exception.

860-001

 

#859 – The Scope of a try Block

A try/catch block consists of:

  • try statement followed by a block of code contained in braces { }
  • One or more catch statements, optionally indicating the type of exception that can be caught

The idea of the try block is to indicate a block of code for which an exception can be caught.  An exception that occurs as a result of calling any of the statements in the try block can be caught in the associated catch block.

In the example below, we catch exceptions that occur in the Dog constructor, the Dog.Bark call, or the Dog.Print call.  An exception thrown from any of these methods, or code that they call, will be caught in the catch block.

                try
                {
                    // Construct a dog
                    Dog d = new Dog("Kirby", 15);

                    // Bark at volume=11
                    d.Bark("Woof", 11);

                    // Print info
                    d.Print();
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Something went wrong.  Message:");
                    Console.WriteLine(exc.Message);
                }

859-001

#854 – Catching an Exception

You can catch an exception by using the combination of a try block and one or more catch clauses.  If any of the statements within the try block throws an exception and the exception type matches what is specified in the catch clause, the code within the catch clause will execute.

In the example below, we try reading from a file within a try block and we have a catch clause that handles exceptions of any type (System.Exception).  The using block disposes of the StreamReader object properly.

            static void Main(string[] args)
            {
                try
                {
                    using (StreamReader sr = new StreamReader(args[0]))
                    {
                        string firstLine = sr.ReadLine();
                        Console.WriteLine(firstLine);
                    }
                }
                catch (System.Exception exc)
                {
                    Console.WriteLine(exc.GetType());
                    Console.WriteLine(exc.Message);
                }
                Console.ReadLine();
            }
        }

If we run this code and pass in a non-existent file name, we see that we catch an exception of type FileNotFoundException.

854-001

#852 – How Exceptions Work

An exception is something that happens in your application at run-time that is unexpected and which requires special logic in order for the application to continue executing normally.

Here’s how exceptions work:

  • A particular piece of code calls a method, which in turn may call other methods
  • The call stack keeps track of the calling sequence that led to the currently executing method
  • At any given time, the code that is executing may decide to throw an exception, indicating that something unexpected happened
  • The method throwing an exception stops what it’s doing and control returns to the calling method
  • The calling method may decide to catch the exception, i.e. execute some code in response to it
  • If the calling method doesn’t catch the exception, control continues back up the stack until a method is found that does catch the exception
  • If no method catches the exception, it is unhandled