Search code examples
c#targetinvocationexception

SetValue property reflection Exception handling issues


When using property reflection to SetValue, the property throws a TargetInvocationException. However, since the call to SetValue is an invocation, the exception is caught and not handled in the property. Is there way to handle the Target Exception in the property and have it ONLY thrown in the main program?

I want this throw to be as if I just made a method call, not an invocation.

Edit for clarification:

The problem I am having is that within the reflect class, I am getting a debug message that says "Exception was unhandled by user code". I have to 'continue' with the debug session and the inner exception is the 'real' exception. Is this just to be expected? I dont want to get warned (and I dont want to hide warnings), I want the code to fix the warning.

public class reflect
{
    private int _i;
    public int i
    {
        get { return _i; }
        set 
        { 
            try{throw new Exception("THROWN");}
            catch (Exception ex)
            { // Caught here ex.Message is "THROWN"
                throw ex; // Unhandled exception error DONT WANT THIS
            } 
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        reflect r = new reflect();
        try
        {
            r.GetType().GetProperty("i").SetValue(r, 3, null);
        }
        catch(Exception ex)
        { // Caught here, Message "Exception has been thrown by the target of an invocation"
            // InnerMessage "THROWN"
            // WANT THIS Exception, but I want the Message to be "THROWN"
        }
    }
}

Solution

  • You need the InnerException:

    catch(Exception ex)
    {
        if (ex.InnerException != null)
        {
            Console.WriteLine(ex.InnerException.Message);
        }
    }
    

    This isn't specific to reflection - it's the general pattern for any exception which was caused by another. (TypeInitializationException for example.)