Background
Exception handling appears in most .NET applications, this post is trying to describe some Exception handling particulars in C# which might not take enough awareness from C# developers.
Differences between throw and throw ex
I guess every C# developer has seen code snippet below:
try
{
// Do some work, exception occurs
}
catch (IOException ex)
{
// Exception caught, re-throw it to bubble up
throw ex;
}
In the catch block, we can rethrow the caught exception instance of IOException to higher level, and we may also saw another way in a little different:
try
{
// Do some work, exception occurs
}
catch (IOException ex)
{
// Exception caught, re-throw it to bubble up
throw;
}
Is there any different?
The answer is yes! To prove that I wrote a simple snippet of code below, first is a simple customized Exception: DummyException.
internal class DummyException : Exception
{
public DummyException(String dummymsg)
: base(dummymsg)
{
}
public DummyException(String dummymsg, Exception innerException)
: base(dummymsg, innerException)
{
}
}
And then I manually throw the DummyException within one method, while handle it in different way mentioned above:
class Program
{
private static void DoLowLevelOperation()
{
// Do some low level operation
throw new DummyException("A dummy exception message!");
}
public static void MethodThrowException1()
{
try
{
DoLowLevelOperation();
}
catch (DummyException de)
{
throw;
}
}
public static void MethodThrowException2()
{
try
{
DoLowLevelOperation();
}
catch (DummyException de)
{
throw de;
}
}
static void Main(string[] args)
{
try
{
MethodThrowException1();
}
catch (DummyException de1)
{
Console.WriteLine(de1.Message);
Console.WriteLine(de1.StackTrace);
}
try
{
MethodThrowException2();
}
catch (DummyException de2)
{
Console.WriteLine(de2.Message);
Console.WriteLine(de2.StackTrace);
}
}
}
The result will be:
。。。