For completeness:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
Also note that you can capture the exception like this:
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print("Handling run-time error:", err)
...and re-raise the exception like this:
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
Also, multiple exception types can be handled as a parenthesized tuple:
try:
i_might_fail()
except (ValueError, TypeError) as ex:
print('I failed with: ', ex)
...examples fromor as separate except clauses:
try:
i_might_fail()
except ValueError:
print('handling a ValueError...')
except TypeError:
print('handling a TypeError...')
...see the python tutorial.