Exception Handling in Python
CBSE Class 12 - Computer Science
🐍 Python Errors and Exceptions Guide
Understanding errors and exceptions is crucial for writing robust Python programs. Learn how to identify, handle, and prevent common errors.
📌 Difference Between Error and Exception
| Term | Meaning |
|---|---|
| Error | General term for issues in code stopping execution. |
| Exception | Type of error handled by try...except blocks. |
🔍 3 Main Types of Errors
🔹 1. Syntax Errors
Occurs due to incorrect Python syntax.
Example:
Error: SyntaxError: expected ':'
Correction:
🔹 2. Runtime Errors (Exceptions)
Errors occurring during code execution.
Example (ZeroDivisionError):
Error: ZeroDivisionError: division by zero
🔹 3. Logical Errors
Program runs without crashing but produces incorrect output.
Example:
🌳 Python Exception Hierarchy
🚩 Common Exceptions with Examples
1. ZeroDivisionError
Dividing by zero.
2. IndexError
Accessing invalid index in list or string.
3. KeyError
Dictionary key not found.
4. ValueError
Correct type but inappropriate value.
5. TypeError
Operation on incompatible types.
6. NameError
Variable/function name not defined.
7. AttributeError
Using incorrect attribute/method.
8. FileNotFoundError
File path incorrect or missing file.
9. PermissionError
Insufficient file permissions.
10. ModuleNotFoundError
Incorrect or missing module.
11. EOFError
Unexpected end of input.
🎯 Try-Except-Else-Finally (Detailed Example)
Execution Flow:
- • Try: Execute potentially risky code.
- • Except: Handle exceptions if they occur.
- • Else: Executes if no exceptions are raised.
- • Finally: Always executes, ideal for cleanup.
Example outputs:
Input: 5
Input: 0
Input: abc
✅ Good Practices
- Handle specific exceptions clearly.
- Include a general exception catch.
- Utilize
elseandfinallyblocks for clean handling and graceful exits.