Handling Errors with Exceptions

Python 3.14 · ✓ verified by execution on 2026-07-25

Handling Errors with Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions.

The try and except Blocks

The try clause is executed first. If an exception occurs during the try clause, the rest of the clause is skipped and the except clause executes.

python
try:
    print('Before division')
    result = 10 / 0
    print('After division')
except ZeroDivisionError:
    print('Cannot divide by zero!')
print('Done')
Output
Before division
Cannot divide by zero!
Done

Catching Multiple Exceptions

You can specify different except blocks for different types of exceptions to handle them appropriately.

python
try:
    int('not_a_number')
except ZeroDivisionError:
    print('Zero division')
except ValueError:
    print('Value error caught')
print('Done')
Output
Value error caught
Done

The else Clause

The optional else clause must follow all except clauses and runs if the try clause does not raise an exception.

python
try:
    print('Trying...')
except ValueError:
    print('ValueError caught')
else:
    print('No errors occurred')
print('Done')
Output
Trying...
No errors occurred
Done

The finally Clause

The finally clause executes as the last task before the try statement completes, regardless of whether an exception occurred.

python
try:
    print('Opening file')
    result = 10 / 2
except ZeroDivisionError:
    print('Error')
finally:
    print('Closing file')
print('Done')
Output
Opening file
Closing file
Done

Raising Exceptions

The raise statement allows the programmer to force a specified exception to occur.

python
try:
    raise ValueError('Custom error message')
except ValueError as e:
    print(f'Caught: {e}')
Output
Caught: Custom error message

Edge Cases

Check yourself

Can a try-except block catch syntax errors?

Reveal answer

No. Syntax errors are detected before the code runs, so try-except can only catch runtime errors. — Syntax errors are detected before the code runs, so try-except can only catch runtime errors.

When does the finally block execute?

Reveal answer

It runs no matter what, whether an exception occurred or not. — The finally block runs no matter what, whether an exception occurred or not.

When does the else clause in a try block run?

Reveal answer

It runs only if NO exception was raised in the try block. — The else clause runs only if NO exception was raised in the try block.

Challenges

Challenge 1 +25 XP

Write a function safe_divide(a, b) that returns a / b, but if a ZeroDivisionError occurs, it returns 0. If a TypeError occurs, it returns 'invalid'.

python
  • Test 1 — expects "5.0\n0\ninvalid\n"
Show solution (0 XP)
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return 0
    except TypeError:
        return 'invalid'

print(safe_divide(10, 2))
print(safe_divide(10, 0))
print(safe_divide(10, 'two'))

Challenge 2 +25 XP

Write a function check_age(age) that raises a ValueError with the message 'Too young' if age is less than 18. Otherwise, it should return 'OK'.

python
  • Test 1 — expects "Too young\nOK\n"
Show solution (0 XP)
def check_age(age):
    if age < 18:
        raise ValueError('Too young')
    return 'OK'

try:
    check_age(15)
except ValueError as e:
    print(e)
print(check_age(20))