C Sharp

Rethrowing an Exception

There will be times after a method has caught an exception and done everything it can in its context that it then rethrows the exception back up the call stack. This is done very simply by using the throw keyword. Here's an example of how that looks: -

using System;
class RethrowApp
{
    static public void Main()
    {
        Rethrow rethrow = new Rethrow();
        try
        {
            rethrow.Foo();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    public void Foo()
    {
        try
        {
            Bar();
        }
        catch(Exception)
        {
            // Handle error.
            throw;
        }
    }
    public void Bar()
    {
        throw new Exception("thrown by Rethrow.Bar");
    }
}

In this example, Main calls Foo, which calls Bar. Bar throws an exception that Foo catches. Foo at this point does some preprocessing and then rethrows the exception back up the call stack to Main by using the throw keyword.

by BrainBellupdated
Advertisement: