It may be worth checking out the Errors and Exceptions docs.
In short, you can specify behaviour for different Exception types using the except ExceptionType:
syntax where ExceptionType
is an Exception
derived from the Python Exception
class - a list of built-in Python exceptions can be found here.
It is important to note that when an Exception
is raised in a try
block, Python will execute the code within the first Except
block that matches the Exception
raised in a top-down manner. For this reason, except Exception:
is usually found at the bottom in a given try
/except
chain as to provide default behaviour for unspecified exceptions that may be raised, it is not first as any Exception
raised will trigger this behaviour and thus would make other Except
statements within the chain moot.
Example
The below example illustrates the above points.
Here eval()
has been used for demonstrative purposes only, please be aware of the inherent dangers of using eval()
before you consider using it in your own code.
def demo(e):
try:
eval(e)
except ZeroDivisionError as e:
print("ZeroDivisionError caught")
print(e)
except IndexError as e:
print("IndexError caught")
print(e)
except Exception as e:
print("Other Exception caught")
print(e)
examples = ["10/0", "[0,1,2][5]", "int('foo')"]
for e in examples:
demo(e)
print()
Output
ZeroDivisionError caught
division by zero
IndexError caught
list index out of range
Other Exception caught
invalid literal for int() with base 10: 'foo'