ArgumentException vs FormatException

来源:互联网 发布:网络安全教育心得体会 编辑:程序博客网 时间:2024/05/16 06:47

今天在写程序的时候,传入的参数格式有问题,到底是抛出 ArgumentException 还是 FormatException呢?

在网上一搜,发现了有人问了一个问题,见 http://stackoverflow.com/questions/2135328/why-does-formatexception-not-inherit-from-argumentexception

这个同学说的是:FormatException 为什么不继承ArgumentException呢,因为MSDN的文档上说:

The exception that is thrown when the format of an argument is invalid, or when a composite format string is not well formed. 

https://msdn.microsoft.com/en-us/library/system.formatexception(v=vs.110).aspx

下面有个人的回答说,这是MSDN书写错误。因为FormatException不一定是参数格式有问题,比如函数BinaryReader.Read7BitEncodedInt 有可能抛出 FormatException, 但是这个方法不需要任何参数。如果他依赖的外部文件格式有问题,也会抛出异常。

回复者原话:

FormatException is not necessarily thrown when a formal argument of a method is invalid. It can also happen if the method is consuming an external resource and the format of the data from the external resource is inappropriate.

For example, BinaryReader.Read7BitEncodedInt will throw FormatException if what it's going to read from a stream is not a valid 7-bit encoded integer. It doesn't take any arguments at all. ArgumentException, on the other hand, should only get thrown when an argument passed as a formal parameter to a method is invalid.

The description you referenced from the MSDN article is more restrictive than FormatExceptionreally is and should be clarified.FormatException 弄明白了,那什么时候用ArgumentException呢?

MSDN 上说 :The exception that is thrown when one of the arguments provided to a method is not valid.  ArgumentException确实只针对参数有问题时,抛出的。

ArgumentException有几个子类,其中两个是 ArgumentNullException 和 ArgumentOutOfRangeException. 我们一般是想把错误信息越详细地暴露越好,所以当满足Argument Null 以及 Out of Range时,优先抛出子类的异常。那什么时候抛出ArgumentException呢?

这个例子来源于:http://www.dotnetperls.com/argumentexception

    int A(string argument)    {// Handle null argument.if (argument == null){    throw new ArgumentNullException("argument");}// Handle invalid argument.if (argument.Length == 0){    throw new ArgumentException("Zero-length string invalid", "argument");}return argument.Length;    }

所以: 对于函数,输入参数的格式有问题时,就抛出 FormatException吧。


FormatException : 输入参数格式有问题 以及 依赖数据格式有问题。

ArgumentException : 当没有其它更具体的类来表达参数有问题时,就用ArgumentException吧。


0 0
原创粉丝点击