An exception is an error that happens while a program is running, such as dividing by zero or opening a file that does not exist. If you do not handle it, the program stops with an error message. Exception handling lets you catch the error and respond to it, so your program keeps working. This lesson covers try, except, else, finally and raise, with output for every example.

Try every example in our online Python compiler.

 

Errors and exceptions

There are two kinds of problems in Python code:

  • Syntax errors happen before the program runs, because the code is not written correctly, for example a missing colon.
  • Exceptions happen while the program runs, even if the syntax is correct.

 

The try and except blocks

Put the risky code in try. If an exception happens, Python jumps to the except block.

try:
    print(10 / 0)
except ZeroDivisionError as e:
    print('Error:', e)

Output:

Error: division by zero

The program does not crash, and e holds the error message.

 

Common exceptions

Exception

When it happens

ZeroDivisionError

Dividing by zero

ValueError

A value has the right type but a wrong content, such as int(‘abc’)

TypeError

An operation is used on the wrong type, such as adding a string and a number

IndexError

A list index is out of range

KeyError

A dictionary key does not exist

FileNotFoundError

A file does not exist

try:
    int('abc')
except ValueError as e:
    print('Error:', e)

try:
    print([1, 2, 3][5])
except IndexError as e:
    print('Error:', e)

try:
    print({'a': 1}['b'])
except KeyError as e:
    print('Missing key:', e)

try:
    print('a' + 1)
except TypeError as e:
    print('Error:', e)

try:
    open('nofile.txt')
except FileNotFoundError as e:
    print('Error:', e)

Output:

Error: invalid literal for int() with base 10: 'abc'
Error: list index out of range
Missing key: 'b'
Error: can only concatenate str (not "int") to str
Error: [Errno 2] No such file or directory: 'nofile.txt'

The wording of an error message can differ slightly between Python versions.

 

Catch more than one exception

Use several except blocks, or put several exceptions in a tuple.

try:
    n = int('x')
except (ValueError, TypeError) as e:
    print('Bad value:', e)

Output:

Bad value: invalid literal for int() with base 10: 'x'

To catch any exception, use except Exception as e. To find out which one happened, print its type:

try:
    x = 1 / 0
except Exception as e:
    print(type(e).__name__)
ZeroDivisionError

Catching every exception can hide real bugs, so prefer the specific ones.

 

else and finally

  • else runs only if no exception happened.
  • finally always runs, whether or not there was an exception. It is used for cleanup, such as closing a file.
def div(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print('Cannot divide by zero')
        return None
    else:
        print('Division ok')
        return result
    finally:
        print('Done')

print(div(10, 2))
print(div(1, 0))

Output:

Division ok
Done
5.0
Cannot divide by zero
Done
None

Notice that “Done” is printed in both cases.

 

Raise your own exception

Use raise to create an exception when your own rule is broken.

def check_age(age):
    if age < 0:
        raise ValueError('Age cannot be negative')
    return age

try:
    check_age(-5)
except ValueError as e:
    print('Error:', e)

Output:

Error: Age cannot be negative

Create a custom exception

Make your own exception by creating a class that inherits from Exception.

class InsufficientFunds(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFunds('Balance is too low')
    return balance - amount

try:
    withdraw(100, 500)
except InsufficientFunds as e:
    print('Error:', e)

Output:

Error: Balance is too low

Common mistakes

  • Using a bare except. It catches everything, including errors you did not expect. Name the exception.
  • Putting too much code in try. Keep only the risky line inside it, so you know what failed.
  • Silently ignoring errors. An empty except block hides problems. At least print or log a message.
  • Wrong order of except blocks. Put specific exceptions before general ones such as Exception.

 

Practice questions

  1. Ask for two numbers in variables and divide them, and handle the division by zero.
  2. Convert the list [‘5’, ‘x’, ‘7’] to numbers, and skip the values that cannot be converted.
  3. Write a function that raises a ValueError when a password is shorter than 8 characters.
  4. Read a file that may not exist, and print a friendly message if it is missing.

 

Summary

  • Put risky code in try, and handle errors in except.
  • else runs if there was no error, and finally always runs.
  • Use raise to create an exception, and a class to define your own.
  • Catch specific exceptions instead of everything.