在 Python 程序中,通常使用 try-except 块捕获异常:
try:
# Do stuff
except ValueError:
# Handle exception
Run Code Online (Sandbox Code Playgroud)
据我所知,在异常处理程序中捕获异常的最佳方法是嵌套的 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 …Run Code Online (Sandbox Code Playgroud)