AmbifulWorksheets
Cheat sheet
CBSE · Class 12 · Computer Science

Exception Handling in Python

Syntax errors and exceptions, the built-in exceptions, raise and assert, and the order in which try, except, else and finally run.

Key ideas

Remember

ZeroDivisionErrordividing by zero with /, // or %
ValueErrorright type, wrong value: int('ten'); L.remove(x) when x is not in L
TypeErrorthe wrong type: '5' + 3; len(42); changing a tuple
IndexError, KeyError, NameErroran index out of range; a missing dictionary key; a name never given a value
EOFError, IOError, ImportErrorreading past the end (pickle.load); a file problem; a missing module
The orderno exception: try, else, finally; an exception: try up to it, except, finally

Watch out

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