Carl Camera

InnerException: Reflection's Best Friend

Using reflection, you've carefully crafted code to extract data from an old COM object. It works great, and you feel a sense of accomplishment. But now someone is in your office saying something about your ASP.NET app that it's not working. My Code?

Of course you took the time when creating the reflection call to log any problems in the called module, so you look into the application trace log and you see this quite annoying error:

Exception has been thrown by the target of an invocation

Hmm. Okay the COM module doesn't like something, but... what? This is not the most informative error message. All it says is that we made a call via reflection and the module we called threw an exception.

To get more information we'll need to use InnerException. From now on, when working with reflection calls, my catch blocks look like this:

catch (Exception ex)
    Logger.Log( ex.Message );
    Logger.Log( ex.InnerException.ToString() );
    Logger.Log( ex.InnerException.Message );

The resulting messages are much more informative. I still have the ex.Message even though it generates the Exception thrown by the target of an invocation message because if something else happens in my code, this message will be informative.