Exception Handling in Python Formulas & Cheat Sheet
Complete chapter-wise reference, step-by-step formula explanations, structured table, and board exam trap warnings.
Core Concepts & Theoretical Foundations
- Errors vs Exceptions: Syntax errors (parsing errors caught during compilation before execution) vs Exceptions (runtime anomalies that disrupt normal instruction flow, e.g. division by zero, missing file).
- Handling Constructs: `try` block (contains code that may raise an exception), `except` block (catches and handles specific exception), `else` block (executes ONLY if no exception occurred in try), `finally` block (executes ALWAYS, used for clean-up/resource closing).
- Explicit Exception Raising: Using the `raise` keyword to trigger custom or built-in exceptions when business constraints are violated.
- Common Built-in Exceptions: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, FileNotFoundError, IOError, ImportError, NameError.
Chapter Formulas & Equations (10 entries)
| # | Topic / Formula Name | Mathematical Form & Equation | Conditions, Meaning & Board Tips |
|---|---|---|---|
| 1 | Standard Try-Except-Else-Finally Syntax Template |
|
Complete flow control ensuring resources like open files and sockets are closed reliably. |
| 2 | Multiple Exception Handling in Single Block |
|
Catches any of the grouped exception types using a tuple syntax. |
| 3 | Explicit Exception Raising with Custom Message |
|
Forces execution into the nearest matching except block or terminates script with traceback. |
| 4 | Assertion Statement Validation |
|
Debugging tool to verify internal invariant conditions. |
| 5 | ZeroDivisionError Trigger Condition |
|
Raised when division or modulo denominator evaluates to numerical zero. |
| 6 | IndexError Trigger Condition |
|
Raised when subscript access exceeds boundaries of list, tuple, or string. |
| 7 | KeyError Trigger Condition |
|
Avoided by using dict.get(key, default) or checking with `if key in dict`. |
| 8 | ValueError Trigger Condition |
|
Occurs during illegal type castings or failed mathematical operations like math.sqrt(-1). |
| 9 | TypeError Trigger Condition |
|
Raised when an operator or function is called on objects of improper types. |
| 10 | Finally Block Invariant Execution Guarantee |
|
Guaranteed execution for closing files, flushing buffers, and releasing database locks. |
Step-by-Step Worked Board Exam Examples
Example 1: Predict the exact console output of the following code: def divide(a, b): try: res = a / b except ZeroDivisionError: print('Cannot divide by zero', end=' ') else: print('Result:', res, end=' ') finally: print('Done') divide(10, 2) divide(10, 0)
1. First call: divide(10, 2):
try block: 10 / 2 = 5.0 (No exception)
else block executes: prints 'Result: 5.0 '
finally block executes: prints 'Done'
Output line 1: 'Result: 5.0 Done'
2. Second call: divide(10, 0):
try block: raises ZeroDivisionError
except block executes: prints 'Cannot divide by zero '
else block is skipped
finally block executes: prints 'Done'
Output line 2: 'Cannot divide by zero Done'.
Example 2: Write a Python function `get_integer_input(prompt)` that repeatedly prompts the user until a valid integer is entered, catching any ValueError.
1. Use a `while True:` loop.
2. Inside `try:` block, attempt `val = int(input(prompt))` and `return val`.
3. Inside `except ValueError:` block, display an error message and let loop repeat.
4. Code implementation:
def get_integer_input(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print('Invalid entry! Please enter a valid whole number.')
Common Mistakes to Avoid in Exam
- Using a bare `except:` without specifying exception type: Catches system exit signals (KeyboardInterrupt, SystemExit), making debugging difficult. Always catch specific exceptions (e.g. `except ValueError:`).
- Misunderstanding the `else` block: The `else` block runs ONLY when the `try` block finishes WITHOUT raising any exception; it does NOT run when an exception is caught.
- Placing cleanup code outside the `finally` block: If an unhandled exception occurs, code outside `finally` never executes; cleanup code (file closing) must be inside `finally`.
- Confusing SyntaxError with Exceptions: A SyntaxError is detected by the Python parser before code execution begins; it cannot be caught at runtime by a `try-except` block in the same script.
Target Practice Questions
Q1. What exception is raised by `L = [1, 2]; print(L[5])`?
Correct Answer: `IndexError: list index out of range`
Q2. What exception is raised by `d = {'a': 1}; print(d['b'])`?
Correct Answer: `KeyError: 'b'`
Q3. State whether code in a `finally` block will execute if the `try` block contains a `return` statement.
Correct Answer: Yes, the code in the `finally` block is guaranteed to execute before the function actually exits with the returned value.
Frequently Asked Questions
Q. What is an Exception in Python?
An exception is a runtime error or abnormal event that occurs during program execution, interrupting the normal sequential instruction flow (e.g. attempting to divide by zero, accessing an out-of-range index).
Q. What is the purpose of the `finally` block?
The `finally` block is guaranteed to execute under all circumstances—whether an exception was raised, caught, or completely unhandled, or even if a `return` statement was executed in try/except. It is used to release external resources (closing file descriptors, releasing network connections).
Q. How does `raise` differ from `assert`?
`raise` explicitly triggers an exception whenever executed. `assert` evaluates a boolean condition and raises an `AssertionError` only if the condition evaluates to False.
Q. What is the base class for all built-in non-system-exiting exceptions in Python?
The base class is `Exception`. System-level exceptions (like `KeyboardInterrupt`, `SystemExit`) inherit from `BaseException`.
Q. Can a `try` block have multiple `except` blocks?
Yes, a `try` block can be followed by multiple `except` blocks to handle different exception types differently. The first matching `except` block from top to bottom executes.