5

I need to rethrow an Exception that was caught and stored elsewhere without losing the stack trace information about when the Exception was first caught/stored. My code looks something like this:

    public void Test()
    {
        int someParameter = 12;
        ExecuteSomeAsyncMethod(someParameter, CallbackMethod);   
    }

    public void CallbackMethod(object result, Exception error)
    {
        //Check for exceptions that were previously caught and passed to us
        if(error != null)
            //Throwing like this will lose the stack trace already in Exception
            //We'd like to be able to rethrow it without overwriting the stack trace
            throw error;

        //Success case: Process 'result'...etc...
    }

I've seen solutions to this problem that use reflection (for example here and here) or use Serialization (for example here) but none of those will work for me in Silverlight (private reflection is not allowed and the classes/methods used in the serialization approach don't exist in Silverlight).

Is there any way to preserve the stack trace that works in Silverlight?

Community
  • 1
  • 1
Stephen McDaniel
  • 2,938
  • 2
  • 24
  • 53

2 Answers2

3

Throw a new exception with the exception as inner exception:

throw new ApplcationException("Error message", error);

The inner exception will keep it's stack trace.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • This is looking like my only option right now. Unfortunately, that could/will interfere with existing code like "catch(SpecificExceptionClass)" or that otherwise checks the Type of the Exception down the road. Ideally, I'd like to avoid wrapping the Exception if at all possible because I don't want consumers to have to start checking InnerExceptions for the "real" exception. – Stephen McDaniel Nov 29 '10 at 23:26
3

You can either use

catch(Exeption)
{
   throw;
}

or

catch(Exception e)
{
   throw new Exception(e);
}

Both will keep the stack trace. The first solution seems not to be possible in your example, but the second should work.

Of cause in your case you would throw the parameter error instead of e.

Jesper Fyhr Knudsen
  • 7,802
  • 2
  • 35
  • 46
  • If you want to mention every possible solution that doesn't work here, you forgot the simplest solution: to not catch the exception at all. ;) – Guffa Nov 29 '10 at 23:24
  • @Guffa, true... but then he won't be able to do any of the logic he seems to want to do when the exception occur. The only reason I mentioned both, is that a simple rewrite of his code might make the first one more attractive. But you are right of cause, not catching the exception, would prevent it from being caught :). – Jesper Fyhr Knudsen Nov 29 '10 at 23:38