By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,728 Members | 1,691 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,728 IT Pros & Developers. It's quick & easy.

Preserving stack trace when reflective method throws Exception

P: n/a
I have some code that calls methods reflectively (the method called and its
parameters are determined by text received in a SOAP message, and I
construct a map from strings to MethodInfos). The code that does the call
looks roughly like:

// do reflective call
response = method.Invoke(obj, params);
catch (TargetInvocationException invokex)
throw invokex.InnerException;

That is, if the called method throws an exception, it's pulled out of the
TargetInvocationException and rethrown, to allow generic exception-handling
code to handle the problem. Among the things this generic code might want
to do is log the stack trace of where the exception occurred. Here lies the

When the inner exception is thrown, its existing stack trace information is
overwritten, so all of the exceptions appear to have begun life at the throw
statement shown above. That is, all the useful stack information is lost.
I'm not sure what to do about this.

The docs advise subclassing Exception when you need to change how the stack
trace is displayed, but that's not appropriate here. These include standard
exceptions like IOException, ArgumentException, etc. It makes no sense to
me that creating a new hierarchy of all the system exceptions is required to
get useful stack trace info.

If I throw the containing exception (i.e. the TargetInvocationException ), I
can preserve stack information (being careful to code "throw" rather than
"throw invokex"), but then I lose the ability to handle exceptions the
natural way, with catch blocks. I'd need a sequence of

if (ex.InnerException is XXXException)

statements instead. This is ugly and a maintenance problem.

The whole issue goes away if the calls are done using delegates instead of
MethodInfos. This is inconvenient here, since different methods have
different signatures, making construction of the argument list tricky.
MethodInfos have the common signature (Object, Object[]). (There are other
reasons delegates would be difficult to use, that I don't have space to
describe here.)

Surely there's a way around this, but what is it? Note that the analogous
problem does not occur in Java. There, the stack trace information that an
exception receives when created is reset only when this is explicitly
requested by calling fillInStackTrace().
Nov 16 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.