C#:我应该抛出 ArgumentException 还是 DirectoryNotFoundException?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1073038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:34:53  来源:igfitidea点击:

C#: Should I throw an ArgumentException or a DirectoryNotFoundException?

c#exception

提问by Svish

I have a method which takes a directory path as a string. In the beginning of the method it checks if this path exists and if not it should throw an exception. I'm thinking it should maybe throw a DirectoryNotFoundExceptionor something instead of a less specific ArgumentException.

我有一个将目录路径作为字符串的方法。在该方法的开头,它检查此路径是否存在,如果不存在,则应抛出异常。我认为它可能应该抛出一个DirectoryNotFoundException或其他东西而不是一个不太具体的ArgumentException.

I read the msdn documentation of that DirectoryNotFoundExceptionand it says that

我阅读了DirectoryNotFoundException它的 msdn 文档,它说

DirectoryNotFoundExceptionuses the HRESULT COR_E_DIRECTORYNOTFOUNDwhich has the value 0x80070003.

DirectoryNotFoundException使用HRESULT COR_E_DIRECTORYNOTFOUND具有值的0x80070003

I don't know what that means exactly, and it looks a bit scary... should I still throw that exception, or should I stick to a regular ArgumentException? Or should I stick to the ArgumentExceptionsimply because it is an argument I am complaining about? Or?

我不知道这到底是什么意思,看起来有点吓人……我应该仍然抛出那个异常,还是应该坚持常规ArgumentException?或者我应该ArgumentException仅仅因为这是我抱怨的论点而坚持?或者?

public void MakeFunOf(string path)
{
    if(!Directory.Exists(path))
        throw new WhatException();
    TellJokeAbout(path);
    PointAndLaughAt(path);
}

采纳答案by Talljoe

If you expect the developer to check for the existence of the directory before calling your method, use ArgumentException. If you want the developer to have the choice of handling the missing directory, use DirectoryNotFound exception.

如果您希望开发人员在调用您的方法之前检查目录是否存在,请使用 ArgumentException。如果您希望开发人员可以选择处理丢失的目录,请使用 DirectoryNotFound 异常。

In other words, "Is it a bugthat the developer told me to access a directory that didn't exist?"

换句话说,“开发人员告诉我访问一个不存在的目录是否是一个错误?”

Personally, I'd use the DirectoryNotFound exception.

就个人而言,我会使用 DirectoryNotFound 异常。

回答by Rob

It's just my opinion (as I have nothing concrete to back it up), but here are my reasons forthrowing DirectoryNotFoundException rather than ArgumentException:

这只是我的意见(因为我没有具体的进行备份),但这里有我的理由投掷DirectoryNotFoundException而不是ArgumentException的:

  • You should throw the most specific/accurate type of Exception that you can to allow the consumer of your code to understand the reason for throwing the exception.
  • Given that Framework methods will throw a DirectoryNotFoundException when you try and do something with a directory that's not present, rather than an ArgumentException, follow the bejaviour of the Framework
  • 您应该抛出最具体/最准确的异常类型,以便让代码的使用者了解抛出异常的原因。
  • 鉴于当您尝试对不存在的目录而不是 ArgumentException 执行某些操作时,框架方法将抛出 DirectoryNotFoundException,请遵循框架的行为

回答by James

Sounds like you should be throwing a DirectoryNotFoundException as ArgumentException is put to better use if the specified parameter is not provided....i.e. its null.

听起来您应该抛出 DirectoryNotFoundException ,因为如果未提供指定的参数,则 ArgumentException 将得到更好的使用......即其 null。

Another option is to create your own exception and throw that instead i.e.

另一种选择是创建自己的异常并抛出该异常,即

[Serializable]
public class InvalidConfigurationException: Exception
{
    public InvalidConfigurationException() : base()
    {
    }

    public InvalidConfigurationException(string message)
        : base(message)
    {
    }

    public InvalidConfigurationException(string message, Exception innerException)
        : base(message, innerException)
    {
    }

    protected InvalidConfigurationException(SerializationInfo info, StreamingContext context) 
        : base(info, context) 
    { 
    }
}

Then you could do:

那么你可以这样做:

public void MakeFunOf(string path)
{    
   if(!Directory.Exists(path))        
       throw new InvalidConfigurationException('Directory entered was invalid or does not exist');
   TellJokeAbout(path);    
   PointAndLaughAt(path);
}

回答by jerryjvl

Referring to the documentation of 'ArgumentException':

参考' ArgumentException'的文档:

ArgumentExceptionis thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. All instances of ArgumentExceptionshould carry a meaningful error message describing the invalid argument, as well as the expected range of values for the argument.

ArgumentException当一个方法被调用并且至少一个传递的参数不符合被调用方法的参数规范时抛出。的所有实例ArgumentException都应携带一个有意义的错误消息,描述无效参数,以及参数的预期值范围。

To the letter this means that the exception choice depends on the specification/documentation of your method.

顾名思义,这意味着例外选择取决于您的方法的规范/文档。

If the path parameter is documented as something like 'Path to an existing file/directory' then you would be justified in throwing an 'ArgumentException' (or derivative) because basically by virtue of the documentation you have made the caller responsible for ensuring the file is actually there.

如果路径参数被记录为类似“现有文件/目录路径”的内容,那么您将有理由抛出“ ArgumentException”(或派生词),因为基本上根据文档,您已经让调用者负责确保文件是实际上在那里。

If the path parameter is documented more generally as 'Path to a file to joke about and laugh at', then I'd say 'DirectoryNotFoundException' is more appropriate.

如果路径参数更一般地记录为“文件路径以开玩笑和嘲笑”,那么我会说“ DirectoryNotFoundException”更合适。

回答by Oliver Friedrich

In my opinion you should check for the correctnes of the argument and throw an ArgumentException then after the check throw an DirectoryNotFoundException. It is a big difference if no argument was given or only a wrong path was specified.

在我看来,您应该检查参数的正确性并抛出 ArgumentException,然后在检查后抛出 DirectoryNotFoundException。如果没有给出参数或只指定了错误的路径,这是一个很大的不同。

void CheckDir(string path)
{
  if(String.IsNullOrEmpty(path))
  {
    throw new ArgumentException("Path not specified.");
  }
   if(!Directory.Exists(path))
  {
    throw new DirectoryNotFoundException();
  }
}