.net - 对于无效的文件名应该抛出哪个异常?

标签 .net exception-handling

我有一个接受文件名作为参数的方法,所有文件名都应该以“.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
  • 系统读取错误 = IOException

  • 如果这对您来说描述性不够,那么创建您自己的异常类:
    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/

    相关文章:

    .net - AsParallel()和内部缓冲区大小

    android - 捕获 AsyncTask 的异常。需要思考

    PHP(或其他): Strategy to deal with exceptions that "cannot occur"

    c# - 从一组重载中获取最佳匹配的重载

    c# - HTML 敏捷包

    c# - 如何将接口(interface)与实现分离

    列表理解中的 Python 异常处理

    java - GUI 应用程序中抛出未经检查的异常

    c# - 在 C# 中使用异常抛出。对性能有影响吗?

    c# - 正则表达式问题