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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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}", <span class="skimlinks-unlinked">DateTime.Now</span>));
        sw.WriteLine(xx.ToString());
        <span class="skimlinks-unlinked">sw.Close</span>();
 
        throw// Re-throw
    }
}


883-001