Python:尝试捕获else而不处理异常。可能吗?

2024-06-26 02:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,想知道是否可以在不处理异常的情况下生成try-catch-else语句?

比如:

try:
    do_something()
except Exception:
else:
    print("Message: ", line) // complains about that else is not intended

Tags: messagelineexception情况语句doelsesomething
2条回答

下面的示例代码演示如何使用pass捕获和忽略异常。

try:
    do_something()
except RuntimeError:
    pass # does nothing
else:
    print("Message: ", line) 

虽然我同意约亨·里采尔的回答很好,但我认为其中可能有一个小疏忽。通过pass处理异常/is/being,只做了什么。所以,实际上,这个异常被忽略了。

如果您真的不想处理异常,那么异常应该是raised。

try:
    do_something()
except RuntimeError:
    raise #raises the exact error that would have otherwise been raised.
else:
    print("Message: ", line) 

相关问题 更多 >