Even correct code meets trouble at runtime — a user types letters where a number is expected, a file is missing, a list index is too big. Without handling, the program crashes. Exception handling lets your program catch these problems and respond gracefully instead of dying. It's the difference between an app that says 'please enter a number' and one that just disappears.
1Errors, exceptions and try / except
Recall the three error types from Class 11: syntax errors (broken grammar, won't run), logical errors (wrong output), and runtime errors. A runtime error that occurs while the program runs is called an exception. Exceptions can be caught and handled; syntax errors cannot (you must fix them).
You handle an exception by putting the risky code in a try block and the response in an except block:
try:
x = 10 / 0 # risky
except ZeroDivisionError:
print("Can't divide by zero!")Without the try/except, dividing by zero would crash the whole program. With it, Python jumps to the except block and carries on. Run it below:
Click Run to execute.
- An exception is a runtime error that occurs while the program runs.
- Put risky code in a
tryblock and the response in anexceptblock. - Handling an exception lets the program continue instead of crashing; syntax errors can't be caught — they must be fixed.
2else, finally, and built-in exceptions
A full handler can have four parts:
try— the code that might fail.except— runs only if a matching exception occurs (you can have several, for different errors).else— runs only if no exception occurred.finally— runs always, error or not. Perfect for cleanup (like closing a file).
Common built-in exceptions
| Exception | Raised when… |
|---|---|
ZeroDivisionError | You divide by zero |
ValueError | A value is the right type but wrong, e.g. int("abc") |
TypeError | An operation gets the wrong type, e.g. "a" + 5 |
NameError | You use a variable that doesn't exist |
IndexError | A list/string index is out of range |
KeyError | A dictionary key doesn't exist |
Click Run to execute.
elseruns only if no exception happened;finallyruns always (used for cleanup).- You can have multiple
exceptblocks for different exception types. - Know the common ones: ZeroDivisionError, ValueError, TypeError, NameError, IndexError, KeyError.
★ Project: a safe number reader
In the playground, build robust code:
- Wrap int("...") in try/except ValueError and print a friendly message on failure.
- Access an index beyond the end of a small list inside a try, and catch the IndexError.
- Look up a missing key in a dictionary and catch the KeyError.
- Add a finally block that prints 'Done' in every case.
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.