我有一个接受文件名作为参数的方法,所有文件名都应该以“.csv”结尾。如果传递了不以 .csv 结尾的文件名,我应该抛出哪个异常?
或者我应该采取不同的方法?
最佳答案
ArgumentOutOfRangeException - 您所描述的内容符合超出范围的异常:
The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
ArgumentException用于验证路径字符串中的字符而不是文件类型。
The path parameter is a zero-length string, contains only white space, or contains one or more invalid characters.
恕我直言,路径验证失败图表如下所示:
ArgumentNullException
ArgumentException
FileNotFoundException
ArgumentOutOfRangeException
UnauthorizedAccessException
操作 = NotSupportedException
如果这对您来说描述性不够,那么创建您自己的异常类:
public class InvalidFileTypeException : System.IO.IOException
{
public InvalidFileTypeException(string path, string acceptedTypeMask)
{
this.Message = string.Format(
"File type '{0}' does not fall within the expected range: '{1}'",
path,
acceptedTypeMask);
}
}
...
throw new InvalidFileTypeException("foo.txt", "*.csv");
关于.net - 对于无效的文件名应该抛出哪个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1421577/