Ker*_*ers 3 python exception python-3.x try-except
首先,如果您认为这不是最佳实践,我很乐意在评论中讨论这一点。
我的问题如下,我尝试根据用户输入查找文件。如果找不到该文件,我会得到一个FileNotFoundError. 这很好,但我想给出一个适当的例外,可以更好地描述问题。用户并不真正知道存在的文件决定某些事情是否可能。所以 aFileNotFoundError可能看起来不合适。所以我目前拥有的是:
try:
x = get_file(...)
except FileNotFoundError as e: # Unsupported version
raise MyOwnException(f"Explaining the problem")
Run Code Online (Sandbox Code Playgroud)
上面的方法有效,但异常看起来像这样:
FileNotFoundError& 堆栈跟踪MyOwnException& 堆栈跟踪我愿意只拥有MyOwnException. 为了实现这一目标,我知道你可以这样做:
try:
x = get_file(...)
except FileNotFoundError as e: # Unsupported version
file_not_found = True
if file_not_found:
raise MyOwnException(f"Explaining the problem")
Run Code Online (Sandbox Code Playgroud)
我还可以使用 . 检查文件是否存在os.path.isfile(file_path)。但我希望有一个更优雅的解决方案,因为通常不鼓励在打开之前检查文件是否存在。
是的,您可以使用以下方法在没有前一个异常上下文的情况下引发异常:
raise MyOwnException("Explaining the problem") from None
Run Code Online (Sandbox Code Playgroud)
请参阅https://docs.python.org/3/tutorial/errors.html#exception-chaining
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |