From the book by Jeffrey Richter:
throw; will not change the origin of the exception, whereas
throw ex; will change the origin of the exception to this statement.
When I try the following program, I get this result:
3: at ... in c:\dev\vs.net\exceptiontest3\form1.cs:line 91
2: at ... in c:\dev\vs.net\exceptiontest3\form1.cs:line 101
1: at ... in c:\dev\vs.net\exceptiontest3\form1.cs:line 101
name of method omitted for shorter lines.
It looks to me as the following happens:
- if the exception is thrown in the try-block, the catch-block will
change the origin when rethrowing
- if the exception is thrown in a nested scope (method call), the catch-
block will not change the origin when rethrowing
If the throw statement is moved to a new method and that method is called
in place of the existing throw statement, the exception origin is not
changed.
Is this correct ? Is there something I've misunderstood here ? Done wrong
?
The reason I'm looking into this is that I'm trying to build a bug
reporting class that will dispatch bug reports into a database for later
handling. I was considering using the line number to distinguish
different exceptions from each other, but if the location I decide to
report it might make the exception be reported twice, then I'll have to
rethink that idea.
Here's the code, simply paste this into an empty winforms app, add a
button and let the event handler call TestMethod1(); The line numbers
might of course vary from what I got but you should see the same effect.
private void TestMethod3()
{
try
{
throw new Exception("Test");
}
catch (Exception ex)
{
foreach (String line in ex.StackTrace.Split('\r', '\n'))
if (line.IndexOf(" in ") > 0)
{
System.Diagnostics.Debug.WriteLine("3: " + line.Trim());
break;
}
throw;
}
}
private void TestMethod2()
{
try
{
TestMethod3();
}
catch (Exception ex)
{
foreach (String line in ex.StackTrace.Split('\r', '\n'))
if (line.IndexOf(" in ") > 0)
{
System.Diagnostics.Debug.WriteLine("2: " + line.Trim());
break;
}
throw;
}
}
private void TestMethod1()
{
try
{
TestMethod2();
}
catch (Exception ex)
{
foreach (String line in ex.StackTrace.Split('\r', '\n'))
if (line.IndexOf(" in ") > 0)
{
System.Diagnostics.Debug.WriteLine("1: " + line.Trim());
break;
}
throw;
}
}