Reputation: 1897
If I have an existing exception object (I'm not in a catch block, I just happen to have been given an exception object), is there any way (re)throw it while preserving it's stack trace?
The context for asking is that I'm writing a RunWorkerCompleted handler. If an error happened while running the background task, then this will have shown up in the Error property of the RunWorkerCompletedEventArgs. To keep the code simple I want to use the same error handling code to trap this, or any error that happens later during the handler. That means I need code like this:
Private Sub OnDone(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
Try
If e.Error IsNot Nothing Then Throw e.Error ' But how do I keep its stack trace?
' do other work that might throw an exception
Catch ex As Exception
' handle any exceptions
End Try
End Sub
I don't think that using an InnerException here (ie. saying something like Throw new Exception(ex)) will work because then I have the problem that my Catch block has no way of knowing whether the exception it's supposed to be handling is the outer one or an inner one.
StackOverflow seems to have various similar questions, but I've not found anything that describes this particular situation.
Upvotes: 0
Views: 593
Reputation: 70307
There is a feature in .NET 4.5 that will do what you want. But since that won't help you now, your only option is to wrap it in another exception.
Upvotes: 1