Learn › Class 12 › Computer Science / Informatics Practices › Python revision, functions, exceptions
Exception handling
Work it out on paper first. Then check the hint or the answer.
1. Which exception does int('abc') raise?
Hint
The type is fine (a string) but the value is not a number.
Answer and explanation
Answer: ValueError
int() cannot convert 'abc', so it raises ValueError.
2. Which exception does [1, 2, 3][5] raise?
Hint
The list has indices 0 to 2.
Answer and explanation
Answer: IndexError
Index 5 is out of range, so Python raises IndexError.
3. How many lines does this print? try: print('A'); x = 1 / 0; print('B') except ZeroDivisionError: print('C') finally: print('D')
Hint
Trace each block in order.
Answer and explanation
Answer: 3
It prints A, then C from except, then D from finally: 3 lines.
4. Which block runs only when the try block finishes without an exception?
Hint
It sits between except and finally.
Answer and explanation
Answer: else
The else block runs only if no exception was raised in try.