【发布时间】:2017-11-10 05:05:27
【问题描述】:
在 Python 程序中,通常使用 try-except 块捕获异常:
try:
# Do stuff
except ValueError:
# Handle exception
我知道在异常处理程序中捕获异常的最佳方法是嵌套的 try-except 块。但是,对于许多嵌套的 try-catch 块,这可能会有点混乱:
try:
# Some assignment that throws an exception if the object is not in the list
try:
# Some assignment function that throws an exception if the the object is not already in the database
# Error Handling
except ValueError:
try:
# Some function that throws an exception if the object does not have an undesired property
# Error Handling
except AttributeError:
try:
# Some function that throws an exception if an error happens
except Exception:
# Exception handling
except ValueError:
# Exception handling
有没有更简洁的方法来做到这一点?比如:
try:
# Some assignment that throws an exception if the object is not in the list
try:
# Some assignment function that throws an exception if the object is not already in the database
except ValueError:
# Some function that throws an exception if the object does not have an undesired property
exceptexcept AttributeError:
# Some function that throws an exception if an error happens
exceptexcept Exception:
# Exception handling
except ValueError:
# Exception handling
【问题讨论】:
-
在您的最后一个区块中,您对
exceptexcept的意图是什么?如果这些只是except,那么您的代码可能会像您期望的那样工作。 (需要注意的是,外部ValueError只会捕获发生在 外部 内部 try 块的异常(因为这些异常至少会被最后一个except Exception块捕获)。 -
我试图在 except 子句中捕获异常,而不是在 try 中。
-
假设您试图在错误处理代码中捕捉错误,那么就没有什么可做的了。您必须使用这种嵌套层次结构。
-
抱歉造成误会,在你描述的情况下我同意coldspeed。
-
就像他们说的,你被嵌套困住了。所以这个故事的寓意是:尽量避免在
except块中使用可能引发异常的代码。 ;)
标签: python exception exception-handling