#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

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

6 Responses to #883 – Re-throwing an Exception

  1. Pingback: Dew Drop – July 9, 2013 (#1,581) | Alvin Ashcraft's Morning Dew

  2. Pingback: #884 – Things You Might Do in an Exception Handler | 2,000 Things You Should Know About C#

  3. Hattie A. Farrell says:

    Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to code size and runtime complexity.

  4. Pingback: #900 – What the Exception Object Contains when You Re-throw an Exception | 2,000 Things You Should Know About C#

  5. Pingback: #901 – Throwing a New Exception from a catch Block | 2,000 Things You Should Know About C#

  6. Pingback: #911 – finally Block Execution When Exception Is Rethrown | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: