In a Python program, one generally catches an exception using a try-except block:
try:
# Do stuff
except ValueError:
# Handle exception
The best way I know of to catch an exception in an exception handler is a nested try-except block. However, with many nested try-catch blocks, this may get a bit messy:
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
Is there a neater way to do this? Something like:
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? If these were simplyexcept, then your code would work, likely as you expect. (With the caveat that the outerValueErrorwould only catch exceptions that occurred outside the inner try block (as those would be caught by, at least, the lastexcept Exceptionblock).exceptblocks that can raise exceptions. ;)