Exceptions

Exceptions

The code which can cause an exception to occur is put in the try block and the handling of the exception is implemented in the exceptblock.

Example:

try:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))

Handling multiple exceptions

Three methods to handle multiple exceptions:

1. Putting all the exceptions in a tuple

try:
    file = open('test.txt', 'rb')
except (IOError, EOFError) as e:
    print("An error occurred. {}".format(e.args[-1]))

2. Separate except blocks

We can have as many except blocks as we want.

Example:

If the exception is not handled by the first except block then it may be handled by a following block, or none at all.

3. Trapping ALL exceptions:

Helpful when you have no idea about the exceptions which may be thrown by your program.

finally clause

The code wrapped in thefinally clause will run whether or not an exception occurred.

Example: to perform clean-up after a script:

try/else clause

We might want some code to run if no exception occurs.

It would run before the finally clause.

Example:

Last updated