One mistake I see developers constantly doing is how they handle and rethrow an exception. A lot of developers catch an exception and rethrow it as shown here (note the throw ex):
private void button1_Click(object sender, EventArgs e)
{
try {
Three();
} catch (Exception ex)
{
throw ex;
}
}
private void Three()
{
try {
Two();
} catch (Exception ex)
{
throw ex;
}
}
private void Two()
{
try {
One();
} catch (Exception ex)
{
throw ex;
}
}
private void One()
{
throw new NotImplementedException("one is not implemented yet");
}
The issue with using throw ex is that it wipes out the stack trace so the exception will look like it actually happened in button1_Click not in the One method.
System.NotImplementedException was unhandled
Message="one is not implemented yet"
Source="ThrowAway.ExceptionExamples"
StackTrace:
at ThrowAway.ExceptionExamples.Form1.button1_Click(Object sender, EventArgs e) in ..\Form1.cs:line 26
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
If you need to catch and rethrow an exception (and this sample certainly does not but is done for illustration purposes). Just call throw (without the ex on the end):
private void button1_Click(object sender, EventArgs e)
{
try {
Three();
} catch (Exception ex)
{
throw;
}
}
private void Three()
{
try {
Two();
} catch (Exception ex)
{
throw;
}
}
private void Two()
{
try {
One();
} catch (Exception ex)
{
throw;
}
}
private void One()
{
throw new NotImplementedException("one is not implemented yet");
}
The stack trace will then show the actuall method that caused the exception:
System.NotImplementedException was unhandled
Message="one is not implemented yet"
Source="ThrowAway.ExceptionExamples"
StackTrace:
at ThrowAway.ExceptionExamples.Form1.One() in ..Form1.cs:line 56
at ThrowAway.ExceptionExamples.Form1.Two() in ..Form1.cs:line 50
at ThrowAway.ExceptionExamples.Form1.Three() in ..Form1.cs:line 38
at ThrowAway.ExceptionExamples.Form1.button1_Click(Object sender, EventArgs e) in ..Form1.cs:line 26
Granted you should never have to catch and rethrow exceptions like this in your app anyways unless you need to change the type of the exception, or if you want to capture and log the exception.