Search code examples
c#.netreflectionsystem.componentmodeltargetinvocationexception

Can a TargetInvocationException thrown from reflection have a null InnerException


Whilst browsing the source code for System.ComponentModel.DataAnnotations.CustomValidationAttribute here, I saw the following code (shortened):

try
{
    methodInfo.Invoke(null, methodParams);
}
catch (TargetInvocationException ex)
{
    if (ex.InnerException != null)
    {
        throw ex.InnerException
    }
    throw;
}

Here, the code checks if ex.InnerException is null. I didn't think that a TargetInvocationException could ever have a null InnerException if it was thrown from reflection invocation.

Is this possible? If so, please provide a scenario where the InnerException can be null.


Solution

  • The MSDN states that

    When created, the TargetInvocationException is passed a reference to the exception thrown by the method invoked through reflection. The InnerException property holds the underlying exception.

    So theoretically using only framework reflection methods it should never be null... theoretically :P

    Of course it can (and will!) be null if you explicitly threw it from the method that was being invoked.