Exceptions help your program handle errors without crashing. The exception hierarchy shows how different errors are related, making it easier to catch and fix them.
Exception hierarchy in Python
BaseException
├── SystemExit
├── KeyboardInterrupt
├── Exception
├── ArithmeticError
├── LookupError
├── ... (other built-in exceptions)
The top of the hierarchy is BaseException, which is the parent of all errors.
Most user errors come from Exception, which is a child of BaseException.
try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
try: x = int('abc') except ValueError: print("Invalid number!")
Exception, including ZeroDivisionError.try: x = 1 / 0 except Exception: print("Some error happened")
This program shows how different exceptions from the hierarchy are caught separately or generally.
def test_errors(value): try: if value == 'zero': result = 1 / 0 elif value == 'key': raise KeyError('missing key') else: result = int(value) print(f'Result is {result}') except ZeroDivisionError: print('Caught a ZeroDivisionError') except KeyError: print('Caught a KeyError') except Exception: print('Caught a general exception') print('Test with zero:') test_errors('zero') print('Test with key:') test_errors('key') print('Test with invalid int:') test_errors('abc') print('Test with valid int:') test_errors('10')
Always catch specific exceptions before general ones to avoid hiding errors.
Use Exception to catch most errors, but avoid catching BaseException unless you really want to catch system-exiting events.
You can create your own exceptions by inheriting from Exception or its children.
Exceptions are organized in a tree called the exception hierarchy.
Catching exceptions from higher in the hierarchy catches more errors.
Use specific exceptions to handle errors clearly and safely.
Practice
Solution
Step 1: Understand Python's exception hierarchy
All exceptions in Python inherit fromBaseException, which is the root of the hierarchy.Step 2: Identify the base class
Exceptioninherits fromBaseException, butBaseExceptionis the top-level base class.Final Answer:
BaseException -> Option BQuick Check:
BaseException is the root of all exceptions [OK]
- Confusing Exception with BaseException
- Thinking Error is a built-in base class
- Choosing RuntimeError as base
Solution
Step 1: Recall exception hierarchy for catching exceptions
CatchingExceptioncatches most errors but excludes system-exiting exceptions likeSystemExitandKeyboardInterrupt.Step 2: Identify correct syntax
except Exception:is the standard way to catch all regular exceptions safely.Final Answer:
except Exception: -> Option CQuick Check:
Use Exception to catch all but system-exiting exceptions [OK]
- Using except BaseException catches system exit too
- Catching only RuntimeError misses many exceptions
- Using except SystemExit catches only exit exceptions
try:
x = 1 / 0
except ArithmeticError:
print('ArithmeticError caught')
except ZeroDivisionError:
print('ZeroDivisionError caught')Solution
Step 1: Understand exception hierarchy for ZeroDivisionError
ZeroDivisionErroris a subclass ofArithmeticError.Step 2: Check which except block matches first
SinceArithmeticErrorcomes beforeZeroDivisionError, the first except block catches the exception.Final Answer:
ArithmeticError caught -> Option AQuick Check:
Parent exception catches before child [OK]
- Expecting ZeroDivisionError block to run first
- Thinking exception order does not matter
- Assuming program crashes without handling
try:
open('file.txt')
except IOError:
print('File error')
except FileNotFoundError:
print('File not found')Solution
Step 1: Understand exception hierarchy between IOError and FileNotFoundError
FileNotFoundErroris a subclass ofIOError.Step 2: Check order of except blocks
The more specific exception (FileNotFoundError) must come before the more general (IOError) to avoid unreachable code.Final Answer:
FileNotFoundError should come before IOError -> Option DQuick Check:
Specific exceptions must precede general ones [OK]
- Putting general exceptions before specific ones
- Assuming IOError and FileNotFoundError are unrelated
- Thinking open() requires mode argument always
KeyboardInterrupt and SystemExit. Which is the best way to write the except block?Solution
Step 1: Recall exception hierarchy for KeyboardInterrupt and SystemExit
BothKeyboardInterruptandSystemExitinherit directly fromBaseException, notException.Step 2: Choose except block that excludes these exceptions
except Exception:catches all exceptions exceptKeyboardInterruptandSystemExit, which is the desired behavior.Final Answer:
except Exception: -> Option AQuick Check:
Exception excludes system-exiting exceptions [OK]
- Using except BaseException catches everything including system exit
- Catching KeyboardInterrupt and SystemExit explicitly when not needed
- Combining Exception with KeyboardInterrupt in except tuple
Ready to prove it?
Pass the test and this pattern moves unknown
