首页 > 解决方案 > 为什么抛出 System.Reflection.TargetInvocationException 而不是 System.UriFormatException?

问题描述

我有一个带有 1 个属性和验证的简单类。我希望System.UriFormatException被抛出,但System.Reflection.TargetInvocationException被抛出无效的 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;
        }
    }
}

如果我改变这个类,使它看起来像下面这样,我调用Validate()我创建的对象,然后我System.UriFormatException抛出了,为什么会有这种差异。理想情况下,我想抛出System.UriFormatException第一个片段。我有一种感觉,是因为在对象实例化过程中被抛出,但想了解更多。

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}");
    }
  }
}

我正在更改代码,以便在对象实例化期间引发异常,而不是稍后使用Validate(). Validate()这让我可以节省几行,以及可能忘记被调用的事实。另外,我知道ValidationAttribute类,我对它不感兴趣。

标签: c#.netexceptionthrow

解决方案


推荐阅读