简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM