Python Tutorial · Working with Data · Lesson 36 of 42

Python Try...Except

Handle errors with try, except, else, finally and raise your own exceptions.

try / except

When an error occurs, Python raises an exception. Catch it to handle the problem gracefully:

Example 1Try it yourself
try:
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero")

try:
    value = int("abc")
except ValueError as error:
    print("Invalid number:", error)

Output

You can't divide by zero
Invalid number: invalid literal for int() with base 10: 'abc'

Catch specific exceptions. A bare except: hides bugs and even catches Ctrl+C.

else and finally

else runs when no exception happened; finally always runs — use it for cleanup.

Example 2Try it yourself
def read_number(text):
    try:
        number = float(text)
    except ValueError:
        print("not a number")
    else:
        print("parsed", number)
    finally:
        print("done with", repr(text))

read_number("3.5")
read_number("x")

Output

parsed 3.5
done with '3.5'
not a number
done with 'x'

Raising exceptions

Raise exceptions to signal invalid input. Custom exception classes make errors easy to catch precisely:

Example 3Try it yourself
class InsufficientFunds(Exception):
    pass

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("amount must be positive")
    if amount > balance:
        raise InsufficientFunds(f"balance {balance} < {amount}")
    return balance - amount

for amount in [30, -5, 500]:
    try:
        print(withdraw(100, amount))
    except (ValueError, InsufficientFunds) as e:
        print(type(e).__name__, "-", e)

Output

70
ValueError - amount must be positive
InsufficientFunds - balance 100 < 500

Test yourself

Which block always runs, whether or not an exception occurred?

  1. else
  2. finally
  3. always
  4. except
Show answer

Answer: finally

Practice next