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:

try:
    file = open('test.txt', 'rb')
except EOFError as e:
    print("An EOF error occurred.")
    raise e
except IOError as e:
    print("An error occurred.")
    raise e

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:

try:
    file = open('test.txt', 'rb')
except Exception as e:
    # Some logging if you want
    raise e

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:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))
finally:
    print("This would be printed whether or not an exception occurred!")

# Output: An IOError occurred. No such file or directory
# This would be printed whether or not an exception occurred!

try/else clause

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

It would run before the finally clause.

Example:

try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # any code that should only run if no exception occurs in the try,
    # but for which exceptions should NOT be caught
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')

# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs. And an error here would NOT be caught
# This would be printed in every case.

Last updated