加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – ArgumentException和Exception之间有什么区别?

发布时间:2020-12-15 23:32:42 所属栏目:百科 来源:网络整理
导读:在我们教授的示例代码中,他有一个看起来像这样的片段: if (name == null || name == "") throw new ArgumentException("name is null or empty"); 另一个看起来像这样的片段: if (!File.Exists(name)){ throw new Exception("File does not exist!");} 我
在我们教授的示例代码中,他有一个看起来像这样的片段:

if (name == null || name == "")
    throw new ArgumentException("name is null or empty");

另一个看起来像这样的片段:

if (!File.Exists(name))
{
    throw new Exception("File does not exist!");
}

我只是想知道不同之处是什么以及为什么一个在另一个之上使用

解决方法

Exception是所有异常的基类. ArgumentException用于表示参数无效.它是Exception的子类.使用catch,您实际上可以根据异常的类型进行过滤,并以不同的方式处理每个异常.

MSDN很好地描述了它:

When you have to throw an exception,you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. You should use a standard exception type under these two conditions:

  • You are throwing an exception that is caused by a usage error (that is,by an error in program logic made by the developer who is calling your method). Typically,you would throw an exception such as ArgumentException,ArgumentNullException,InvalidOperationException,or NotSupportedException. The string you supply to the exception object’s constructor when instantiating the exception object should describe the error so that the developer can fix it. For more information,see the Message property.
  • You are handling an error that can be communicated to the caller with an existing .NET Framework exception. You should throw the most derived exception possible. For example,if a method requires an argument to be a valid member of an enumeration type,you should throw an InvalidEnumArgumentException (the most derived class) rather than an ArgumentException.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读