Exception Types, try, except, else, and finally
Key Takeaways
- A try block contains code that may raise an exception; matching except blocks decide whether execution can recover.
- Exception handlers are checked from top to bottom, so specific handlers should appear before broad handlers.
- The else block runs only when the try block completes without raising an exception.
- The finally block runs after try, except, or else paths and is commonly used for cleanup.
- PCEP-level exception recognition includes TypeError, ValueError, IndexError, KeyError, NameError, and ZeroDivisionError.
What an exception changes
An exception interrupts normal statement-by-statement execution. If code in a try block raises an exception, Python stops the remaining try-block statements and searches the attached except clauses from top to bottom. If one matches, that handler runs. If none matches, the exception continues outward.
try:
n = int('8')
print(10 / n)
except ValueError:
print('bad number')
except ZeroDivisionError:
print('zero')
The conversion succeeds, division succeeds, and no handler runs. The snippet prints 1.25.
Common PCEP exception types
| Exception | Typical cause in exam snippets |
|---|---|
NameError | Reading a name that is not defined |
TypeError | Wrong operand type or wrong function arguments |
ValueError | Right type, invalid value, such as int('abc') |
IndexError | List, tuple, or string index out of range |
KeyError | Missing dictionary key with bracket lookup |
ZeroDivisionError | Division or modulo by zero |
The distinction between TypeError and ValueError is especially useful. int(3.5) works because the type is acceptable. int('abc') raises ValueError because a string is acceptable in general, but that specific string cannot be converted to an integer.
Collection errors have a similar pattern. letters[9] can be IndexError because list indexes are valid in general but that position does not exist. record['age'] can be KeyError because dictionary key lookup is valid, but that key is absent.
Handler order
Handlers are tested in written order. A broad handler placed first can catch an exception before a later specific handler has any chance.
try:
values = [1, 2]
print(values[5])
except Exception:
print('general')
except IndexError:
print('index')
This prints general, not index. IndexError is a kind of Exception, so the first matching handler wins. Better code puts except IndexError before except Exception.
else and finally
The else clause runs only if the try block finishes without an exception. The finally clause runs whether an exception occurred, was handled, or did not occur. In ordinary PCEP snippets, assume finally runs before control leaves the try statement.
try:
item = {'a': 1}['b']
except KeyError:
print('missing')
else:
print('found')
finally:
print('done')
The dictionary lookup raises KeyError. The except block prints missing; the else block is skipped; the finally block prints done.
Continuation after handling
If an exception is handled, execution continues after the whole try statement.
try:
print(int('x'))
except ValueError:
print('handled')
print('after')
The output is handled and then after. The failed print inside the try block never completes because int('x') raises ValueError first.
If the handler itself raises a new exception, normal continuation does not happen. PCEP snippets may hide this by putting another risky expression inside the except block. Trace the handler body just as carefully as the original try block.
Exam tracing routine
For exception snippets, write down:
- The first statement in the try block that can fail.
- The exact exception type raised.
- The first except clause that matches.
- Whether else is skipped or executed.
- What finally prints or changes before the snippet continues or the error escapes.
This routine prevents two common mistakes: running statements after the failing line inside the try block, and choosing the most specific handler instead of the first matching handler.
Which exception is most likely from int('abc')?
Why should except IndexError usually appear before except Exception in a small PCEP snippet?
When does the else clause of a try statement run?