SetValue property reflection Exception handling issues

926 Views Asked by At

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"
        }
    }
}
2

There are 2 best solutions below

2
On BEST ANSWER

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.)

2
On

Sorry, can't comment yet. Two things: 1) why are you first catching ex in your reflection class and then throwing it again? This shouldn't be the problem, though. 2) I think you are getting your exception. Check the "Exception has been thrown"'s inner exception.