This is a follow-up question to Is there a difference between “throw” and “throw ex”?
is there a way to extract a new error handling method without resetting the stack trace?
[EDIT] I will be trying both "inner method" and another answer provided by Earwicker and see which one can work out better to mark an answer.
Are you catching exceptions that you want to then filter more carefully, so you can then change your mind, decide not to handle them and so rethrow them?
If you want to be really careful about this, that's not really a good idea. It's better to never catch the exception in the first place. The reason is that a given
try/catch
handler should not take the decision to run nestedfinally
blocks for exceptions that it is not expecting to see. For example, if there is aNullReferenceException
, it's probably a very bad idea to continue executing any code as it will probably cause another such exception to be thrown. Andfinally
blocks are just code, like any other code. As soon as an exception is caught for the first time, anyfinally
blocks on the stack beneath thetry/catch
will be executed, by which time it's too late - another exception may be generated, and this means that the original exception is lost.This implies (in C#) that you have to careful write out a separate
catch
handler for all the exception types you want to catch. It also implies that you can only filter by exception type. This is sometimes very hard advice to follow.It should be possible to filter exceptions in other ways, but in C# it is not. However, it is possible in VB.NET, and the BCL itself takes advantage of this by having a small amount of code written in VB.NET so it can filter exceptions in a more convenient way.
Here's a detailed explanation, with a VB.NET code sample, from the CLR team blog.
And here's my two cents.
You don't want to create a new exception with the original stack trace. That is misleading, since that stack trace did not create the new exception.
You can, however, put the original exception in your new exception as an "InnerException". Would that do what you are looking for?
Not sure if you mean that, but my suggestion in your other question was addressing this.
If your handler returns a boolean whether the exception was handled or not, you can use this in your catch clause:
With .NET Framework 4.5 there is now an ExceptionDispatchInfo which supports this exact scenario. It allows capturing a complete exception and rethrowing it from somewhere else without overwriting the contained stack trace.
code sample due to request in comment
Yes; That's what the InnerException property is for.
This will allow you to add your own logic, then throw your own exception class. The StackTrace of the YourExceptionClass instance will be from within this code block, but the InnerException will be the exception you caught, with the StackTrace it had before.