Concept Flow - Exception hierarchy
BaseException
Exception
ValueError
ZeroDivisionError
Exceptions in Python form a tree starting from BaseException. Most errors inherit from Exception, which branches into specific error types.
Jump into concepts and practice - no test required
try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero")
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Execute 'x = 1 / 0' | 1 / 0 | Raises ZeroDivisionError |
| 2 | Catch exception | Is exception ZeroDivisionError? | Yes |
| 3 | Run except block | print message | Outputs: Cannot divide by zero |
| 4 | End try-except | No more code | Program continues normally |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| x | undefined | exception raised, no assignment | undefined | undefined |
Python exceptions form a hierarchy starting at BaseException. Most user errors inherit from Exception. You catch exceptions using try-except blocks. Catching a parent exception catches all its children. Example: catching Exception catches ZeroDivisionError. Use specific exceptions to handle errors precisely.
BaseException, which is the root of the hierarchy.Exception inherits from BaseException, but BaseException is the top-level base class.Exception catches most errors but excludes system-exiting exceptions like SystemExit and KeyboardInterrupt.except Exception: is the standard way to catch all regular exceptions safely.try:
x = 1 / 0
except ArithmeticError:
print('ArithmeticError caught')
except ZeroDivisionError:
print('ZeroDivisionError caught')ZeroDivisionError is a subclass of ArithmeticError.ArithmeticError comes before ZeroDivisionError, the first except block catches the exception.try:
open('file.txt')
except IOError:
print('File error')
except FileNotFoundError:
print('File not found')FileNotFoundError is a subclass of IOError.FileNotFoundError) must come before the more general (IOError) to avoid unreachable code.KeyboardInterrupt and SystemExit. Which is the best way to write the except block?KeyboardInterrupt and SystemExit inherit directly from BaseException, not Exception.except Exception: catches all exceptions except KeyboardInterrupt and SystemExit, which is the desired behavior.