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
Your output
Catching Multiple Exceptions
You can specify different except blocks for different types of exceptions to handle them appropriately.
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
Your output
Edge Cases
If a finally block contains a return statement, it overrides any return statement in the try block.
An exception raised inside an except block will crash the program unless caught by an outer try-except block.
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))