2

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.

Bassie
  • 9,529
  • 8
  • 68
  • 159
H Bellamy
  • 22,405
  • 23
  • 76
  • 114
  • How about `void Foo() { throw new TargetInvocationException(null); }`. The point is, `TargetInvocationException` might not be thrown from reflection, but from user code - it is public class, has public constructor that does not require non null inner exception. – Ivan Stoev Sep 12 '16 at 11:56
  • @IvanStoev thanks - I'm specifically asking for a TIE thrown from reflection, however – H Bellamy Sep 12 '16 at 12:40
  • Why do you think it should be from reflection? Get `MethodInfo` of my `Foo` method via reflection, `Invoke` it and here you go. – Ivan Stoev Sep 12 '16 at 13:07
  • But I see your point. Actually in my previous comment, my Foo `TargetInvocationException` will be wrapped as inner exception of the TIE thrown by the reflection. So, yeah, probably make no sense, just a safety code style. – Ivan Stoev Sep 12 '16 at 13:13
  • 2
    That programmer is never going to be sorry. It is the kind of excessive caution that is not unusual in the .NET Framework, it avoids at least one support call :) His life would have been easier if the TargetInvocationException constructor would never allow a null argument but that did not happen. Having an exception constructor itself throw an exception is pretty brutal. – Hans Passant Sep 12 '16 at 14:33

1 Answers1

2

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.

Scott Perham
  • 2,410
  • 1
  • 10
  • 20