Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c# - Why System.Reflection.TargetInvocationException is thrown instead of System.UriFormatException?

I have a simple Class with 1 property and validation on set. I expect System.UriFormatException to be thrown, but System.Reflection.TargetInvocationException is thrown on invalid uri.

public class MyClass
{
    private string _baseUrl;

    public string BaseUrl
    {
        get => _baseUrl;

        set
        {
            if (!Uri.IsWellFormedUriString(value, UriKind.Absolute))
            {
                throw new UriFormatException($"Host is not valid Uri: {BaseUrl}");
            }

            _baseUrl = value;
        }
    }
}

If I change this class so it looks like as is below and I call Validate() on the object I have created, then I have System.UriFormatException thrown, why is there this difference. Ideally, I would like to throw System.UriFormatException with the first snippet. I have a feeling that is caused because is thrown during object instantiation but would like to know more about it.

public class MyClass {

public string BaseUrl { get; set; }

public void Validate () {
    if (!Uri.IsWellFormedUriString (BaseUrl, UriKind.Absolute)) {
        throw new UriFormatException ($"Host is not valid Uri: {BaseUrl}");
    }
  }
}

I am changing the code, so that exception is thrown during instantiation of the object, and not later with Validate(). That allows me to save few lines, and also the fact that Validate() maybe forgotten to be called. Also, I am aware of ValidationAttribute class and I am not interested in it.

question from:https://stackoverflow.com/questions/65943867/why-system-reflection-targetinvocationexception-is-thrown-instead-of-system-urif

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...