Hi,
Thanks Dave. [Actually I posted here by error. Sorry. The message was
for the VB group.]
Anyway, on this point I have been confused by some statement in this
article:
http://www.codeproject.com/dotnet/exceptionbestpractices.asp
where the author says that
Throw ex
is wrong and I should always use
Throw
So I 'd like to hear opinions on that.... Thank you
-P
First, the CodeProject example is in C#, where "throw;" is legal. I am
not sure if it is in VB.NET.
In C#, the idea to use "throw;" instead of "throw ex;" is, as explained
in the article, to avoid modifying the stack trace.
Every exception object has a stack trace, which allows you to see where
it comes from. It is a string representation of the call stack at the
time where the exception was thrown.
However, when you do "throw ex;", it clears the stack trace and
everything appears as if the exception was thrown from there.
Consider the following code:
private void ExecuteThrow()
{
try
{
NestedMethod1();
}
catch ( Exception )
{
Console.WriteLine( "Exception caught" );
throw;
}
}
private void ExecuteThrowEx()
{
try
{
NestedMethod1();
}
catch ( Exception ex )
{
Console.WriteLine( "Exception caught" );
throw ex;
}
}
private void NestedMethod1()
{
NestedMethod2();
}
private void NestedMethod2()
{
NestedMethod3();
}
private void NestedMethod3()
{
throw new ArgumentException( "This is a dummy exception only" );
}
If I call ExecuteThrow, the stack trace is the following:
at temp.NestedMethod3() in
d:\GalaSoft\myhtml\GalaSoft\_current\temp.aspx.cs:line 77
at temp.NestedMethod2() in
d:\GalaSoft\myhtml\GalaSoft\_current\temp.aspx.cs:line 72
at temp.NestedMethod1() in
d:\GalaSoft\myhtml\GalaSoft\_current\temp.aspx.cs:line 67
at temp.ExecuteThrow() in
d:\GalaSoft\myhtml\GalaSoft\_current\temp.aspx.cs:line 48
at temp.bnExecute_Click(Object sender, EventArgs e) in
d:\GalaSoft\myhtml\GalaSoft\_current\temp.aspx.cs:line 26
If I call ExecuteThrowEx, the stack trace is:
at temp.ExecuteThrowEx() in
d:\GalaSoft\myhtml\GalaSoft\_current\temp.aspx.cs:line 61
at temp.bnExecute_Click(Object sender, EventArgs e) in
d:\GalaSoft\myhtml\GalaSoft\_current\temp.aspx.cs:line 30
I lost the whole path to NestedMethod3. That's the idea in this article.
HTH,
Laurent