Python Try...Except

Python has a mechanism, called "try-except" (or "try-catch" in many other programming languages) that you can use to gracefully handle an exception. This is much more preferable than having the entire program "crash" because of a runtime error. When an exception is raised and the program "catches" it, the program can try to remedy the situation in different ways depending on what the program is doing. For example:

  1. If the program is actually a service that other programs call, one can return an error including an informative message, as the error is often caused by bad inputs.
  2. If the program is getting some values from the user, the program can print a useful message to the user and ask the user to input a new value.
  3. If the program expecting another service to be working, like a connection to a database, the program might send an email to someone telling them that the connection to the database has stopped working.

As you can see, how you handle exceptions is very dependant on the kind of program you are writing and how it will be used by others.

The syntax for handling is to wrap the code that might throw an exception in a try block, then handle possible exceptions in the except block:

Python
try:
    # Some code that might throw an exception.
except:
    # Code that handles the exception.

Example

Python
try:
    a = 1 / 0
except:
    print("oops, division by 0")

The except block can specify the exact exception (see below) to be handled:

Example

Python
try:
    a = 1 / 0
except ZeroDivisionError:
    print("oops, division by 0")

The except block can specify one or more exceptions (see below) that are your code will handle in the same way. Multiple exceptions handled by the same code are comma separated exception types listed within parentheses:

Example

Python
try:
    a = 1 / 0
except (ZeroDivisionError, ValueError):
    print("oops, division by 0")

One can write several except blocks to handle each exception type differently:

Example

Python
try:
    a = 1 / 0
except ZeroDivisionError:
    print("oops, division by 0")
except ValueError:
    print("Some other error with the values.")

You can also get the message that Python provides for the exception, which is often useful to pass on to the user or to log in an error file:

Example

Python
try:
    a = 1 / 0
except ZeroDivisionError as err:
    print(err)

Output

division by zero

The keyword finally is used to tell Python, whether the code in the try block succeeds or raises an exception, always execute the code in the finally block.

Example

Python
try:
    a = 1 / 0
except ZeroDivisionError as err:
    print(err)
finally:
    print('Did you get your answer?')

Output

division by zero
Did you get your answer?

Your program can also raise an exception with the raise keyword.

Example

Python
numerator = 1
denominator = 0

if (denominator == 0):
    raise ZeroDivisionError
else:
    print(numerator / denominator)

Output

Traceback (most recent call last):
  File "errorHandling.py", line 5, in <module>
    raise ZeroDivisionError
ZeroDivisionError