#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

Advertisements