#911 – finally Block Execution When Exception Is Rethrown

Recall that if an exception is caught in a catch block, an associated finally block will execute after the execution of the catch block.

If the catch block rethrows the exception, the finally block will execute after the catch block, but before the exception propagates back up the call stack.

In the example below, the sequence is:

  • Exception thrown from try block in HelperMethod
  • Exception caught in catch block in HelperMethodcatch block executes up to throw
  • finally block in HelperMethod executes
  • Exception caught in catch block of Main method
        static void Main(string[] args)
        {
            try
            {
                HelperMethod();
            }
            catch
            {
                Console.WriteLine("Caught exception in Main()");
            }

            Console.ReadLine();
        }

        static void HelperMethod()
        {
            try
            {
                throw new ApplicationException("Uh-oh");
            }
            catch
            {
                Console.WriteLine("In catch block, before re-throwing");
                throw;
            }
            finally
            {
                Console.WriteLine("In finally block");
            }
        }

911-001

Advertisement

#901 – Throwing a New Exception from a catch Block

Within a catch block, you can rethrow the original exception using the throw statement.  This allows any method further up in the call stack to also handle the exception.

There are also cases when you want to throw an exception that is different from the exception that you just caught.  You can do this using the throw new syntax and by storing the original exception in the new exception’s InnerException property.

In the example below, the code in the DoDogStuff method catches a DogBarkException, handles it, and then throws a new (more general) exception.

        static void Main(string[] args)
        {
            try
            {
                DoDogStuff();
            }
            catch (Exception xx)
            {
                Console.WriteLine("** Exception in Main():");
                Console.WriteLine(xx.ToString());
            }
        }

        static void DoDogStuff()
        {
            try
            {
                Dog d = new Dog("Kirby", 15);
                d.Bark(BarkSound.Woof, 99);
            }
            catch (DogBarkException xx)
            {
                Console.WriteLine(string.Format("** DogBarkException: Can't bark {0} times!", xx.NumTimes));
                throw new ApplicationException("Failure to do dog stuff", xx);
            }
        }

901-001

#883 – Re-throwing an Exception

When you catch an exception in an exception handler, you have the option of executing some code and then re-throwing the exception.  When you re-throw an exception from a handler, code that called the current method has the option of also handling the exception.  Alternatively, if no higher-level handler exists, the exception will be treated as an unhandled exception after you re-throw it.

In the example below, DoSomeStuff catches all exceptions, writes information to a log file and then re-throws the exception.

        private const string MyLogFile = "App1.log";

        static void Main(string[] args)
        {
            Console.WriteLine("About to do some stuff");

            try
            {
                DoSomeStuff();
            }
            catch (Exception xx)
            {
                Console.WriteLine(xx.ToString());
            }

            Console.ReadLine();
        }

        static void DoSomeStuff()
        {
            try
            {
                Dog d1 = new Dog("Jack", 15);
                Dog d2 = new Dog("Kirby", 150);
            }
            catch (Exception xx)
            {
                StreamWriter sw = new StreamWriter(MyLogFile, true);  // append
                sw.WriteLine(string.Format("Exception at {0}", DateTime.Now));
                sw.WriteLine(xx.ToString());
                sw.Close();

                throw;  // Re-throw
            }
        }

883-001

#881 – When to Throw Exceptions

Your code should throw an exception when

  • Something has gone wrong and your code cannot execute normally
  • You catch an exception and want to add some additional information
  • You catch an exception and your application cannot gracefully recover from the problem

Some examples of when you might throw an exception:

  • Parameter value that is out of range passed to a function
  • Parameter values that are inconsistent passed to a function
  • Invalid values passed to function (e.g. username with wrong password)
  • Function called while application is in the wrong state 

Do not throw exceptions

  • As part of normal operation, to control program flow
  • To return data back to code that called a function
  • Just to indicate which function was executing when an exception was caught

#873 – Full Example of Throwing and Catching an Exception

Below is a complete example of throwing an exception from a method and catching/handling that exception further up the call stack.

Code for Dog class that throws an exception if we ask a dog to bark too many times:

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        // Dog constructor
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        // Dog.Bark
        public void Bark(int numTimes)
        {
            if (numTimes > 10)
                throw new ArgumentException(
                    string.Format("{0} is just too many times to bark", numTimes));

            for (int i = 1; i <= numTimes; i++)
                Console.WriteLine("Woof");
        }
    }

Code that calls the Bark method, with an exception handler in the Main() method:

        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Before MethodA call");
                MethodA();
                Console.WriteLine("After MethodA call");
            }
            catch (Exception xx)
            {
                Console.WriteLine(
                    string.Format("Caught in Main(): {0}",
                                  xx.Message));
            }

            Console.ReadLine();
        }

        private static void MethodA()
        {
            Console.WriteLine("Before MethodB call");
            MethodB();
            Console.WriteLine("After MethodB call");
        }

        private static void MethodB()
        {
            Dog d = new Dog("Kirby", 15);
            d.Bark(99);
            Console.WriteLine("I barked 99 times");
        }

Below is the output.
873-001

#872 – Code After a throw Statement Is Not Executed

When you throw an exception using the throw statement, control transfers immediately to the calling function.  No additional statements in the method containing the throw statement are executed.

In the example below, if you call the Bark method and pass in a value for numTimes that is greater than 10, an exception is thrown.  In this case, the for loop will never execute–i.e. the dog won’t bark.

        // Dog.Bark
        public void Bark(int numTimes)
        {
            if (numTimes > 10)
                throw new ArgumentException(
                    string.Format("{0} is just too many times to bark", numTimes));

            for (int i = 1; i <= numTimes; i++)
                Console.WriteLine("Woof");
        }

#856 – Choosing an Exception Type to Throw

When you throw an exception, you create and populate an instance of the System.Exception class, or one of its derived classes.

While it’s possible to throw an exception of type System.Exception, it’s not normally recommended.  You typically want to throw as specific an exception as possible, for two reasons:

  • To provide some specific details about what went wrong (e.g. filename that could not be found, rather than just a general message).
  • To allow an exception handler to catch specific types of exceptions

Typically, when throwing an exception, you do one of the following:

  • Throw an exception whose type matches one of the predefined exception types in the .NET Framework.  (E.g. System.ArgumentException)
  • Throw an instance of System.ApplicationException and provide a relevant message
  • Define your own custom exception type, which inherits from System.Exception, and throw an instance of that type.

#855 – Throwing an Exception

Your code can throw an exception to indicate that some sort of error occurred.  You’ll typically do this to indicate that something has gone wrong and the execution of the method cannot continue.

To throw an exception, you create an instance of the System.Exception class, or one of its derived classes, to contain information about what went wrong.  You use the throw statement to throw the exception.  Control returns immediately to the calling function and the exception “bubbles up” the call stack, looking for a calling method that can handle the exception.

Below, an exception is thrown if numTimesToBark is too large.

        public void Bark(int numTimesToBark)
        {
            if (numTimesToBark > 10)
            {
                string message =
                    string.Format("Dogs can bark at most 10 times.  {0} is too much barking",
                                  numTimesToBark);
                Exception exc = new Exception(message);
                throw exc;
            }

            for (int i = 0; i < numTimesToBark; i++)
                Console.WriteLine("Woof");
        }

#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

#178 – Throwing an Exception from a switch Statement

Instead of a break statement as a terminator of a case clause in a switch statement, you can also throw an exception.

            switch (surname)       // surname is a string
            {
                case "Aarhus":
                case "Enevoldsen":
                    Console.WriteLine("Norwegian");
                    break;
                case "Brosnan":
                case "McGill":
                    Console.WriteLine("Irish");
                    throw new ApplicationException("Software doesn't work for Irish people");
                default:
                    Console.WriteLine("UNKNOWN origin");
                    break;
            }