简体   繁体   English

是否应该为不存在的文件参数引发ValueError或OSError?

[英]Should I raise ValueError or OSError for non-existent file arguments?

When a program receives a filename argument that does not exist, or is not a directory, I want to raise an error. 当程序收到不存在或不是目录的文件名参数时,我想引发一个错误。 But what error is considered best practice? 但是什么错误被认为是最佳实践?

I understand that ValueError is often used to signal invalid arguments (and I've seen several questions about it). 我知道ValueError通常用于表示无效的参数(并且我已经看到了几个有关它的问题 )。 I also understand that, especially after the reorganization of exceptions in Python 3.3 ( PEP 3151 ), OSError is the catch-all category for problems related to interaction with the system. 我也了解到,尤其是在Python 3.3( PEP 3151 )中重新组织了异常之后, OSError是与系统交互相关的问题的综合类。

So, I have a program that expects a filename argument. 因此,我有一个期望文件名参数的程序。 If the name supplied by the caller does not exist, or exists but is a directory, what error should I raise? 如果调用方提供的名称不存在,或者存在但仅是目录,我应该引发什么错误? It's an incorrect argument so it seems that ValueError applies; 这是一个错误的参数,因此似乎ValueError适用; but if I try to read from it as a file, I will get an OSError -- so shouldn't this be returned for consistency? 但是,如果我尝试从文件中读取文件,则会收到OSError -难道不应该为了一致性而返回此错误?

does it really matter?(I assume you are not catching this exception and it is purely for informational purposes of an individual looking at the terminal output) none of that will be seen by the operating system as such I would just 真的重要吗?(我假设您没有捕获此异常,并且它纯粹是出于个人查看终端输出的信息目的),操作系统将不会看到任何异常,我只是

raise Exception("Invalid Arguments, expected a file that exists not %r"%(filename))

or just let it fail when it tries to open the file naturally even 或尝试自然打开文件时让它失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM