Class XII · Chapter 1Unit 1, Computational Thinking and Programming, 2 (40 marks)5 min read
Chapter 1: Exception Handling in Python
CBSE Unit: Unit 1, Computational Thinking and Programming, 2 (40 marks) Marks Weightage: ~3-5 marks (1 MCQ + 1 short answer typically) Priority: HIGH, small chapter but guaranteed questions
Key Concepts
1.1 Syntax Errors vs Exceptions
- Syntax errors (parsing errors): detected before execution, program won't run until fixed
- Exceptions: errors during execution of syntactically correct code (runtime errors)
- Important: SyntaxError is technically also an exception, but all other exceptions occur when code is syntactically correct
1.2 Built-in Exceptions (MUST memorize)
| Exception | When Raised | Example |
|---|---|---|
SyntaxError |
Rules of language not followed | print("hello" (missing parenthesis) |
ValueError |
Right type but wrong value | int("hello") |
IOError |
File cannot be opened | open("nonexistent.txt") |
KeyboardInterrupt |
User presses Delete/Esc during execution | Ctrl+C during input() |
ImportError |
Module not found | import nonexistent_module |
EOFError |
End of file reached by input() | Ctrl+D during input() |
ZeroDivisionError |
Division by zero | 10/0 |
IndexError |
Index out of range | lst[100] on small list |
NameError |
Variable not defined | Using x without defining it |
IndentationError |
Incorrect indentation | Missing indent after if: |
TypeError |
Wrong data type for operation | "hello" + 5 |
OverFlowError |
Result exceeds numeric limit | Very large calculations |
1.3 Raising Exceptions
The raise Statement
raise exception_name[(optional_argument)]
- Forces an exception to be raised, Statements after
raiseare NOT executed, Can raise built-in or user-defined exceptions
# Example
length = 10
numbers = [1, 2, 3]
if length > len(numbers):
raise IndexError("List index out of range")
print("This will NOT execute")
The assert Statement
assert Expression[, arguments]
- Tests an expression, if False, raises
AssertionError - Commonly used at beginning of functions to validate input
def negativecheck(number):
assert(number >= 0), "OOPS... Negative Number"
print(number * number)
negativecheck(100) # Output: 10000
negativecheck(-350) # AssertionError: OOPS... Negative Number
1.4 Handling Exceptions, try/except/else/finally
Basic try-except
try:
# code that might raise exception
numerator = 50
denom = int(input("Enter denominator: "))
quotient = numerator / denom
print("Division successful")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("This executes regardless")
Multiple except blocks
try:
numerator = 50
denom = int(input("Enter denominator: "))
print(numerator / denom)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Only integers allowed")
Generic except (catch-all), must be LAST
try:
# code
except ValueError:
print("Value error")
except:
print("Some other error occurred")
try-except-else
elseblock executes ONLY if NO exception was raised in try
try:
quotient = numerator / denom
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result is:", quotient) # Only if no error
try-except-else-finally
finallyblock ALWAYS executes, with or without exception, Used for cleanup operations (closing files, releasing resources)
try:
quotient = numerator / denom
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", quotient)
finally:
print("This ALWAYS executes")
Critical point: If exception is raised and NO matching except handler exists, the finally block still executes FIRST, then the exception is re-raised.
Flow Summary
try block → (exception?) → YES → matching except block → finally
→ NO → else block → finally
Important Definitions for Board Exam
| Term | Definition |
|---|---|
| Exception | A Python object that represents an error during execution |
| Exception Handling | Writing additional code to handle errors and prevent program crash |
| Throwing an exception | Creating an exception object and handing it to runtime system |
| Catching an exception | Executing the handler code designed for that exception |
| Call stack | The list of methods searched (in reverse order) to find exception handler |
Common Board Exam Question Patterns
- MCQ: Which exception is raised when... (1 mark)
- MCQ: What is the output of code with try-except? (1 mark)
- Fill in blanks: Complete a try-except-else-finally block (2 marks)
- Short answer: Differentiate between syntax error and exception (2 marks)
- Short answer: What is the use of raise/assert statement? (2 marks)
- Program: Write code with exception handling for division/file/input (3 marks)
Key Points Students Miss
finallyexecutes even if exception is NOT handled by any except blockelseexecutes only when NO exception occurs, not "otherwise"- After
raise, remaining statements in that block are skipped assertraisesAssertionErrorspecifically, not a generic error- Multiple except blocks: order matters, generic
except:must be LAST SyntaxErrorIS an exception (confuses students who think only runtime errors are exceptions)
Exercise Answers (Key)
Q1: "Every syntax error is an exception but every exception cannot be a syntax error", SyntaxError is a type of exception. But exceptions like ValueError, ZeroDivisionError etc. are not syntax errors, they occur in syntactically correct code.
Q7 Fill in blanks: ValueError, ZeroDivisionError, finally
Prefer watching over reading?
Subscribe for free.