my question is similar to Using reflection, setter throws exception which can't be caught, but the recommended solution does not solve my problem.
In the code below, I try to set the property of a class via two different ways: first, directly and second, via reflection. The setter throws an exception (in the real use case only if the given value is invalid) that should be caught at the place where the setter is called. But the exception is only caught in the first variant; in the second, the catch-block is never executed. What is the reason for this?
In my use case, I want to use the reflection variant but the program always terminates where the exception is thrown and I have no change to catch it.
The mentioned thread above recommends that either the Debugger is configured in such a way that it breaks at every exception (this cannot be the case as in the first variant, the exception is caught perfectly fine) or that the exception comes from somewhere else. Unfortunately, I do not know where it could come from otherwise.
Thank you very much for your help!
using System;
using System.Reflection;
namespace ReflectionTestConsole
{
public class Program
{
public static void Main(string[] args)
{
Logic logic = new Logic();
try
{
logic.MyProperty = 5;
}
catch(Exception e)
{ // in this case, the exception is caught here.
Console.WriteLine("Exception was caught: " + e.Message);
}
try{
PropertyInfo propInfo = logic.GetType().GetProperty("MyProperty");
propInfo.SetValue(logic,5);
}
catch (Exception e)
{ // in this case, the exception is not caught
Console.WriteLine(e.Message);
}
}
}
public class Logic
{
private double variable;
public double MyProperty
{
get
{
return variable;
}
set
{ //Check if value is valid and if not throw an exception
throw new Exception("This is the exception");
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire