我可以在 except 子句中抛出自定义异常而不导致:“在处理...期间”

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)。但我希望有一个更优雅的解决方案,因为通常不鼓励在打开之前检查文件是否存在。

khe*_*ood 5

是的,您可以使用以下方法在没有前一个异常上下文的情况下引发异常:

raise MyOwnException("Explaining the problem") from None
Run Code Online (Sandbox Code Playgroud)

请参阅https://docs.python.org/3/tutorial/errors.html#exception-chaining