Learn/Python/9. Handling errors
Lesson 9 of 15
Sign in

Python, lesson 9

Handling errors

Things go wrong in real programs: a user types ten where you expected a number, a file is missing, someone divides by zero. Python reports these problems by raising an exception. If nothing handles it, the program stops and prints a traceback. Handling exceptions lets your program react sensibly instead of crashing.

try and except

Put the risky code in a try block and say what to do in an except block:

If int() fails, Python jumps straight to the matching except block; the rest of the try block is skipped. If nothing fails, the except block is skipped.

Always name the exception type you expect. A bare would also swallow typos and other bugs you'd much rather see.

2 exercises to try what you just read.

Exercise 1

Careful calculator

Press Ctrl Enter or Check to test your code.

Exercise 2

Piggy bank

Press Ctrl Enter or Check to test your code.

except:

Common built-in exceptions

ExceptionTypical cause
ValueErrorright type, bad value: int("abc")
TypeErrorwrong type: "3" + 4
ZeroDivisionErrordividing by zero
IndexErrorlist index out of range
KeyErrormissing dictionary key
FileNotFoundErroropening a file that isn't there

They are all classes that inherit from Exception. An except clause also catches subclasses of the type it names.

Several handlers, else and finally

A try statement can have several except clauses, checked in order. You can also catch several types in one clause. Since Python 3.14 the parentheses are optional when you don't use as, but they work in every version:

as err gives you the exception object, whose text explains what went wrong. The else block keeps the "success" code out of the try, so you don't accidentally catch errors from it. finally is for cleanup that must always happen, such as closing a connection.

Raising your own exceptions

When your own function receives something it can't work with, raise an exception rather than returning a strange value. The caller then decides how to handle it:

Custom exception classes

For errors that belong to your program's own rules, define a class that inherits from Exception. The class body can be empty; the name alone carries the meaning:

Callers can now write except OutOfStockError: and handle exactly that case while letting anything unexpected through.

Ask forgiveness, not permission

Python code often just tries the operation and handles the failure, instead of checking every condition first. Converting text with int() inside try is simpler and more reliable than inspecting each character yourself.

Further reading

  • The Python Tutorial: Errors and exceptions
  • Built-in exceptions

Each input line holds two values separated by a space. For each line, divide the first by the second and print the result with two decimals. Instead of crashing:

  • if either value is not a number, print error: not a number
  • if the second value is zero, print error: division by zero

Sample input:

Sample output:

The first line is the starting balance (a whole number). Each following line is either deposit N or withdraw N. Write withdraw(balance, amount) so it raises the custom exception InsufficientFunds when the amount is larger than the balance, and returns the new balance otherwise. When a withdrawal fails, print declined: balance is B (with the current balance) and carry on. At the end print final: B.

Sample input:

Sample output:

text = input()
try:
    age = int(text)
    print(f"Next year you'll be {age + 1}")
except ValueError:
    print(f"'{text}' is not a whole number")
try:
    a, b = input().split()
    result = int(a) / int(b)
except ZeroDivisionError:
    print("Can't divide by zero")
except (ValueError, TypeError) as err:
    print(f"Bad input: {err}")
else:
    print(result)              # runs only if nothing was raised
finally:
    print("Calculation done")  # runs no matter what
def set_volume(level):
    if not 0 <= level <= 10:
        raise ValueError(f"volume must be 0-10, got {level}")
    return level
class OutOfStockError(Exception):
    pass

def take(stock, amount):
    if amount > stock:
        raise OutOfStockError(f"only {stock} left")
    return stock - amount
10 4
7 0
abc 2
2.50
error: division by zero
error: not a number
50
withdraw 20
withdraw 40
deposit 15
declined: balance is 30
final: 45