Reputation: 45
I am using reflection to set properties on an object. If any of the setters throw an exception, the exception is not caught by the code that makes the SetValue call. Visual Studio tells me that the exception is uncaught by user code.
For example, imagine in the example below that the Title property setter on the object referenced by the "target" variable throws an ArgumentException
.
Looking at the call stack, it seems that there is unmanaged code between the snippet below and the setter.
Can somebody please (& thank you!) explain:
Here is my code:
try
{
prop.SetValue(target, attr.Value); // target does have a "Title" property
// attr.Value == "Title"
// the setter throws an ArgumentException
}
catch (Exception ex) // No exception is ever caught.
{
errors.Add(ex.Message);
}
Here is the code for one of many properties that I want to set like this: public string Title { get { return this.title; }
set
{
if (string.IsNullOrEmpty(value) || value.Length < 1 || value.Length > 128)
{
throw new ArgumentException("Title must be at least 1 character and cannot be longer than 128 characters.");
}
this.title = value;
}
}
Upvotes: 1
Views: 813
Reputation: 13972
Any exception there should be caught.
See fiddle: https://dotnetfiddle.net/koUv4j
This includes errors in the reflection call itself (setting the property to the wrong Type
), or having an exception within the property's setter itself (set
throws).
This leads to something else being wrong. Possibilities:
catch
, which will rethrow
)If it's not one of those 2 then please provide more information.
Upvotes: 0
Reputation: 15151
EDIT as stated by @Default, Framework 4.5 does have an overload with only two parameters, so if the user is working with FW 4.5 this answer does not have relevance (at least the last part about PropertyInfo),
You are wrong, it is trapped and here is an example to demonstrate it:
public class ExceptionGenerator
{
public static void Do()
{
ClassToSet clas = new ClassToSet();
Type t = clas.GetType();
PropertyInfo pInfo = t.GetProperty("Title");
try
{
pInfo.SetValue(clas, "test", null);
}
catch (Exception Ex)
{
Debug.Print("Trapped");
}
}
}
class ClassToSet
{
public string Title {
set {
throw new ArgumentException();
}
}
}
What you are doing wrong is obtaining the PropertyInfo, the PropertiInfo's SetValue method expects a third parameter, the index at the property (null in your case), so your "prop" is not a PropertyInfo, I assume it's a FieldInfo, and because that it throws an unhandled exception.
Upvotes: 1