When throwing an exception preserving the stack trace is the most common desired behavior, and in Java this can be obtained with throw ex;
, but in C# throw;
must be used. (Please also notice that many of C# programmers will often wrongly use throw ex;
instead of throw;
).
If sometime the stack trace must be cleared (which is a less frequent situation), it is possible to just throw a new exception like throw new MyException(ex.Message, otherDetails);
.
So, considering the above, which is the advantage of having a separate throw;
statement in C#?
Or, in other words: why is C# using a special separate statement (throw;
), which is less known, for the most used case (when the user wants to preserve the stacktrace), and it uses the more natural throw ex;
for the less frequent case (when the stacktrace is cleared)? Is there any other possible use case for which I didn't cover?
Code sample in C# and Java:
// This is the C# design
try
{
//...
}
catch (MyException ex)
{
// rethrow so that stack trace is preserved
ex.AppendData(contextVariable);
throw;
}
catch (PrivateException ex)
{
// throw new exception so stack trace is not preserved
throw new PublicException(ex.Message);
}
// This is the Java design
try
{
//...
}
catch (MyException ex)
{
// rethrow so that stack trace is preserved
ex.AppendData(contextVariable);
throw ex;
// and I can even choose to use something like, where ProcessException(ex) will return the same ex
throw ProcessException(ex, contextVariable);
}
catch (PrivateException ex)
{
// throw new so stack trace is not preserved
throw new PublicException(ex.getMessage());
}