In my code I’m coming across a situation in which a System.Reflection.TargetInvocationException is thrown. In one specific case I know how I want to handle the root exception, but I want to throw all other exceptions. I can think of two ways of doing this, but I’m not sure which is better.
1.
try
{
//code
}
catch (System.Reflection.TargetInvocationException ex)
{
if (typeof(ex.InnerException) == typeof(SpecificException))
{
//fix
}
else
{
throw ex.Innerexception;
}
}
2.
try
{
//code
}
catch (System.Reflection.TargetInvocationException ex)
{
try
{
throw ex.InnerException;
}
catch (SpecificException exSpecific)
{
//fix
}
}
I’m aware that throwing exceptions in general is slow, so I feel the first method would possibly be faster. Alternatively, is there a better way of doing this that I haven’t thought of?
Each of your proposed solutions has its own issue.
The first method checks that the type of the inner exception is exactly the type you’re expected. That means that a derived type won’t match, which might not be what you intended.
The second method overwrites the inner exception’s stack trace with the current stack location, as Dan Puzey mentioned. Destroying the stack trace may be destroying the one lead you require in order to fix a bug.
The solution is basically what DarkGray posted, with Nick’s suggestion and with an added suggestion of my own (in the
else):If you want to re-throw an exception that turns out you can’t handle, don’t
throw ex;since that will overwrite the stack trace. Instead usethrow;which preserves the stack trace. It basically means “I actually didn’t want to enter thiscatchclause, pretend I never caught the exception”.Update: C# 6.0 offers a much better syntax via Exception Filters: