Bird
Raised Fist0
Pythonprogramming~10 mins

Exception hierarchy in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.
Execution Sample
Python
try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
This code tries to divide by zero and catches the ZeroDivisionError to print a message.
Execution Table
StepActionEvaluationResult
1Execute 'x = 1 / 0'1 / 0Raises ZeroDivisionError
2Catch exceptionIs exception ZeroDivisionError?Yes
3Run except blockprint messageOutputs: Cannot divide by zero
4End try-exceptNo more codeProgram continues normally
💡 Exception caught by ZeroDivisionError handler, program does not crash.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
xundefinedexception raised, no assignmentundefinedundefined
Key Moments - 3 Insights
Why is x not assigned after the division by zero?
Because the exception occurs during the calculation, the assignment never happens (see execution_table step 1).
Why does the program not crash after the error?
The ZeroDivisionError is caught by the except block (execution_table step 2), so the program handles it gracefully.
What if we catch Exception instead of ZeroDivisionError?
Catching Exception would also catch ZeroDivisionError because it is a subclass (see concept_flow showing hierarchy).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 1?
Ax is assigned the value 0
BA ZeroDivisionError is raised
CThe except block runs
DThe program ends
💡 Hint
Check the 'Evaluation' and 'Result' columns in execution_table row 1.
According to variable_tracker, what is the value of x after step 2?
A0
B1
Cundefined
DNone
💡 Hint
See variable_tracker row for x after step 2.
If we replaced 'except ZeroDivisionError' with 'except Exception', what would happen?
AThe exception would be caught and handled
BThe program would crash
CThe exception would not be caught
DA different exception would be raised
💡 Hint
Refer to concept_flow showing Exception is a parent of ZeroDivisionError.
Concept Snapshot
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.
Full Transcript
In Python, errors are organized in a hierarchy starting from BaseException. Most common errors inherit from Exception. For example, ZeroDivisionError is a child of Exception. When code runs, if an error happens, Python looks for a matching except block to handle it. If you try to divide by zero, Python raises ZeroDivisionError. If you have a try-except block catching ZeroDivisionError, it will run the except code and prevent the program from crashing. Variables are not assigned if an exception happens during their assignment. Catching a parent exception like Exception will also catch its child exceptions like ZeroDivisionError. This helps you handle errors broadly or specifically.

Practice

(1/5)
1. Which of the following is the base class for all built-in exceptions in Python?
easy
A. Exception
B. BaseException
C. Error
D. RuntimeError

Solution

  1. Step 1: Understand Python's exception hierarchy

    All exceptions in Python inherit from BaseException, which is the root of the hierarchy.
  2. Step 2: Identify the base class

    Exception inherits from BaseException, but BaseException is the top-level base class.
  3. Final Answer:

    BaseException -> Option B
  4. Quick Check:

    BaseException is the root of all exceptions [OK]
Hint: Remember: BaseException is the root of all exceptions [OK]
Common Mistakes:
  • Confusing Exception with BaseException
  • Thinking Error is a built-in base class
  • Choosing RuntimeError as base
2. Which of the following is the correct syntax to catch all exceptions except system-exiting ones?
easy
A. except SystemExit:
B. except BaseException:
C. except Exception:
D. except RuntimeError:

Solution

  1. Step 1: Recall exception hierarchy for catching exceptions

    Catching Exception catches most errors but excludes system-exiting exceptions like SystemExit and KeyboardInterrupt.
  2. Step 2: Identify correct syntax

    except Exception: is the standard way to catch all regular exceptions safely.
  3. Final Answer:

    except Exception: -> Option C
  4. Quick Check:

    Use Exception to catch all but system-exiting exceptions [OK]
Hint: Use except Exception to avoid catching system-exit errors [OK]
Common Mistakes:
  • Using except BaseException catches system exit too
  • Catching only RuntimeError misses many exceptions
  • Using except SystemExit catches only exit exceptions
3. What will be the output of this code?
try:
    x = 1 / 0
except ArithmeticError:
    print('ArithmeticError caught')
except ZeroDivisionError:
    print('ZeroDivisionError caught')
medium
A. ArithmeticError caught
B. ZeroDivisionError caught
C. No output, program crashes
D. SyntaxError

Solution

  1. Step 1: Understand exception hierarchy for ZeroDivisionError

    ZeroDivisionError is a subclass of ArithmeticError.
  2. Step 2: Check which except block matches first

    Since ArithmeticError comes before ZeroDivisionError, the first except block catches the exception.
  3. Final Answer:

    ArithmeticError caught -> Option A
  4. Quick Check:

    Parent exception catches before child [OK]
Hint: Parent exceptions catch before child exceptions in order [OK]
Common Mistakes:
  • Expecting ZeroDivisionError block to run first
  • Thinking exception order does not matter
  • Assuming program crashes without handling
4. Find the error in this code snippet:
try:
    open('file.txt')
except IOError:
    print('File error')
except FileNotFoundError:
    print('File not found')
medium
A. open() needs a mode argument
B. IOError should be replaced with Exception
C. No error, code is correct
D. FileNotFoundError should come before IOError

Solution

  1. Step 1: Understand exception hierarchy between IOError and FileNotFoundError

    FileNotFoundError is a subclass of IOError.
  2. Step 2: Check order of except blocks

    The more specific exception (FileNotFoundError) must come before the more general (IOError) to avoid unreachable code.
  3. Final Answer:

    FileNotFoundError should come before IOError -> Option D
  4. Quick Check:

    Specific exceptions must precede general ones [OK]
Hint: Place child exceptions before parent exceptions in except blocks [OK]
Common Mistakes:
  • Putting general exceptions before specific ones
  • Assuming IOError and FileNotFoundError are unrelated
  • Thinking open() requires mode argument always
5. You want to catch all exceptions except KeyboardInterrupt and SystemExit. Which is the best way to write the except block?
hard
A. except Exception:
B. except BaseException:
C. except (KeyboardInterrupt, SystemExit):
D. except (Exception, KeyboardInterrupt, SystemExit):

Solution

  1. Step 1: Recall exception hierarchy for KeyboardInterrupt and SystemExit

    Both KeyboardInterrupt and SystemExit inherit directly from BaseException, not Exception.
  2. Step 2: Choose except block that excludes these exceptions

    except Exception: catches all exceptions except KeyboardInterrupt and SystemExit, which is the desired behavior.
  3. Final Answer:

    except Exception: -> Option A
  4. Quick Check:

    Exception excludes system-exiting exceptions [OK]
Hint: Use except Exception to exclude system-exiting exceptions [OK]
Common Mistakes:
  • Using except BaseException catches everything including system exit
  • Catching KeyboardInterrupt and SystemExit explicitly when not needed
  • Combining Exception with KeyboardInterrupt in except tuple