Tuesday, March 11, 2008

How to rethrow exception in C#.

When a exception is caught and it is necessary to process the exception and rethrow it, then statement throw can be used.

If it is necessary to throw new exception:

try
{
throw exp;
}
catch (Exception e)
{
Debug.Write(e.Message); // Exception processig

throw new Exception("DoException", e);
}
If it is necessary to throw caught exception next:
try
{
throw exp;
}
catch (Exception e)
{
Debug.Write(e.Message); // Exception processig

throw;
}

First code will generate exception System.Exception and second code will generate exception exp (in our test sample Exception1).
Console output:
consoleOutput_RethrowException 

All sources can be download from google code project csharp-tips "google code" project

Additional Links:

throw (C# Reference)

1 comment:

Anonymous said...

http://www.aired.in/2009/06/c-questions-on-exception-handling-and.html