Learn › Class 12 › Computer Science / Informatics Practices › Python revision, functions, exceptions
Exception handling
You will learn to
- Tell syntax errors from runtime exceptions
- Name common built-in exceptions
- Use try, except, else and finally, and raise exceptions
Helpful to know first: Functions in Python; Input and type conversion.
A syntax error breaks Python's grammar, such as a missing colon. Python reports it before the program runs. An exception is an error that happens while the program runs.
Common exceptions
ZeroDivisionError: dividing by zero. ValueError: int('abc'). TypeError: '5' + 5. NameError: an undefined name. IndexError: a list index out of range. KeyError: a missing dictionary key. FileNotFoundError: opening a missing file.
Put risky code in a try block. If an exception occurs, Python jumps to the matching except block, and the program does not crash.
You can have several except blocks; put specific exceptions before general ones. The else block runs only if no exception occurred. The finally block always runs, so it is used for clean-up.
You can signal a problem yourself with raise, for example raise ValueError('marks must be 0 to 100'). The assert statement raises AssertionError when a condition is false.
Common mix-ups
Not quite: try and except can catch a missing colon or bracket.
Instead: Syntax errors stop the program before it runs, so no except block ever gets the chance to catch them.
Not quite: The finally block runs only when there is an error.
Instead: finally runs every time, with or without an exception.