Worksheets › Class 12 › Exception Handling in Python › Cheat sheet
Class 12 Exception Handling in Python: cheat sheet
CBSE Computer Science. Syntax errors and exceptions, the built-in exceptions, raise and assert, and the order in which try, except, else and finally run.
Key ideas
- A syntax error (or an IndentationError) is reported before the program runs; an exception is raised while a correct program runs.
- When a line in try raises an exception, the rest of try is skipped and the first matching except runs.
- else runs only when try finished with no exception; finally always runs, even just before a function returns.
- After the handler and finally, the program carries on with the line after the whole try statement.
- An exception that no except matches stops the program, once finally has run; an except with no name catches every exception.
- raise throws an exception on purpose; assert condition raises an AssertionError when the condition is False.
Remember
| ZeroDivisionError | dividing by zero with /, // or % |
| ValueError | right type, wrong value: int('ten'); L.remove(x) when x is not in L |
| TypeError | the wrong type: '5' + 3; len(42); changing a tuple |
| IndexError, KeyError, NameError | an index out of range; a missing dictionary key; a name never given a value |
| EOFError, IOError, ImportError | reading past the end (pickle.load); a file problem; a missing module |
| The order | no exception: try, else, finally; an exception: try up to it, except, finally |
Watch out
- Thinking else runs after an exception has been handled: it runs only when there was none.
- Forgetting that finally runs in every case.
- Calling a missing colon a runtime error: it is a SyntaxError, found before the program runs.
- Expecting the rest of try to run after the line that raised the exception.
Worked example
Write the letters this prints, in order, separated by commas. try: x = 2 y = x / 0 print('A') except ZeroDivisionError: print('B') else: print('E') finally: print('C') print('D')
Working: x / 0 raises ZeroDivisionError, so A and else are skipped; finally always runs; then the program carries on
Answer: B, C, D
Practise Exception Handling in Python
Revise with this page, then practise: every Exception Handling in Python sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.