Chapter 01 - Exception Handling
1.1 Introduction
While executing a Python program, the program may:
- Not execute at all
- Execute partially
- Terminate abruptly
- Produce unexpected output
These problems occur due to errors in the program.
Types of Errors
- Syntax Errors – detected before execution
- Runtime Errors (Exceptions) – occur during execution
- Logical Errors – program runs but gives wrong output
👉 Exception Handling is the mechanism used to handle runtime errors, so that the program does not crash abruptly.
📌 In Python, runtime errors are represented using exception objects.
1.2 Syntax Errors
What are Syntax Errors?
Syntax errors occur when Python grammar rules are violated.
📌 Detected by the Python interpreter before execution.
Examples of Syntax Errors
print("Hello World"
➡ Missing closing bracket
if x == 10
print(x)
➡ Missing colon
for i in range(5)
print(i)
➡ Incorrect indentation
Important Points
- Program does not execute until syntax errors are corrected
- Also called parsing errors
Python displays:
- Error name
- Line number
- Error description
📌 SyntaxError is also an exception, but it is detected earlier than other exceptions.
1.3 Exceptions
What is an Exception?
An exception is a runtime error that occurs while the program is executing.
📌 Even if syntax is correct, execution may fail.
Common Situations Causing Exceptions
- Division by zero
- Accessing a non-existing file
- Invalid type conversion
- Using an undefined variable
Example
print(10 / 0)
➡ ZeroDivisionError
print(x)
➡ NameError
int("abc")
➡ ValueError
Key Concept
- When an error occurs, Python raises an exception
- If not handled, the program terminates abnormally
1.4 Built-in Exceptions
Python provides many predefined exceptions for common runtime errors.
Common Built-in Exceptions (NCERT Important)
| Exception | Raised When |
|---|---|
SyntaxError |
Invalid syntax |
ValueError |
Wrong value |
TypeError |
Wrong data type |
ZeroDivisionError |
Division by zero |
IndexError |
Index out of range |
NameError |
Variable not defined |
ImportError |
Module not found |
EOFError |
End of input |
IndentationError |
Incorrect indentation |
Example Demonstrations
a = [1, 2, 3]
print(a[5]) # IndexError
import maths # ImportError
print(5 + "A") # TypeError
1.5 Raising Exceptions
Python allows programmers to explicitly raise exceptions.
🔸 1.5.1 raise Statement
Used to forcefully trigger an exception.
Syntax
raise ExceptionName("Error message")
Example
age = -10
if age < 0:
raise ValueError("Age cannot be negative")
📌 Once raise is executed:
- Normal flow stops
- Control jumps to exception handler
- Remaining code is skipped
🔸 1.5.2 assert Statement
Used to test conditions during program execution.
Syntax
assert condition, "Error message"
Example
def square(n):
assert n >= 0, "Negative number not allowed"
return n * n
print(square(5))
print(square(-3))
➡ Raises AssertionError for invalid input
📌 Mostly used for:
- Debugging
- Input validation
1.6 Handling Exceptions
Exception handling prevents abrupt program termination.
Why Exception Handling is Needed?
- Improves program reliability
- Prevents crashes
- Provides meaningful error messages
- Separates error handling code from main logic
🔸 1.6.1 try – except Block
Syntax
try:
# risky code
except ExceptionName:
# handling code
Example
try:
x = int(input("Enter number: "))
print(10 / x)
except ZeroDivisionError:
print("Division by zero not allowed")
🔸 Multiple except Blocks
try:
x = int(input("Enter number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Only integers allowed")
📌 Python checks except blocks top to bottom
🔸 Generic except
except:
print("Some error occurred")
📌 Must always be last except block
🔸 try – except – else
elseexecutes only if no exception occurstry: x = int(input()) y = int(input()) print(x / y) except ZeroDivisionError: print("Zero not allowed") else: print("Division successful")
1.7 Finally Clause
What is finally?
The finally block always executes, whether:
- Exception occurs
- Exception does not occur
- Exception is handled or not
Syntax
try:
# code
except:
# handler
finally:
# always executed
Example
try:
f = open("data.txt")
print(f.read())
except FileNotFoundError:
print("File not found")
finally:
print("Program ended")
📌 Used mainly for:
- Closing files
- Releasing resources
- Cleanup operations
📝 NCERT EXAM SUMMARY (Very Important)
- Syntax errors → detected before execution
- Exceptions → runtime errors
raise→ manually throws exceptionassert→ tests conditionelse→ executes only if no exceptionfinally→ executes always- Unhandled exception → program crashes
Board-Level Solved Programs (CBSE Standard)
Program 1: Handle Division by Zero
Question: Write a program to divide two numbers and handle division by zero.
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
📌 Concept tested: try–except, ZeroDivisionError
Program 2: Handle Invalid Input (ValueError)
try:
num = int(input("Enter an integer: "))
print("Square:", num * num)
except ValueError:
print("Error: Please enter a valid integer")
📌 Concept: ValueError
Program 3: Handle Multiple Exceptions
try:
x = int(input("Enter numerator: "))
y = int(input("Enter denominator: "))
print(x / y)
except ZeroDivisionError:
print("Denominator cannot be zero")
except ValueError:
print("Only integers are allowed")
📌 Very common board question
Program 4: Generic Exception Handling
try:
print(a)
except:
print("Some error occurred")
📌 Concept: Generic except
Program 5: Use of else Block
try:
a = int(input())
b = int(input())
print(a / b)
except ZeroDivisionError:
print("Division by zero")
else:
print("Division successful")
📌 Key point: else runs only if no exception
Program 6: Use of finally Block
try:
f = open("test.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found")
finally:
print("Program execution completed")
📌 Exam favourite
Program 7: Raise an Exception Manually
age = int(input("Enter age: "))
if age < 0:
raise ValueError("Age cannot be negative")
else:
print("Valid age")
Program 8: Use of assert
def check_positive(n):
assert n > 0, "Number must be positive"
print("Valid number")
check_positive(5)
check_positive(-2)
📌 Concept: AssertionError
Program 9: Handle NameError
try:
print(x)
except NameError:
print("Variable is not defined")
Program 10: Handle TypeError
try:
print(5 + "A")
except TypeError:
print("Invalid operation between incompatible types")
Program 11: File Handling with Exception
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
print("File does not exist")
Program 12: Input Until Valid Integer
while True:
try:
num = int(input("Enter integer: "))
break
except ValueError:
print("Invalid input, try again")
print("You entered:", num)
Program 13: Nested try–except
try:
try:
x = int(input())
print(10 / x)
except ZeroDivisionError:
print("Inner: Zero division")
except ValueError:
print("Outer: Invalid input")
Program 14: EOFError Handling
try:
text = input("Enter text: ")
print(text)
except EOFError:
print("End of file reached")
Program 15: Exception Without Handler (Conceptual)
print(10 / 0)
CASE-STUDY QUESTIONS (CBSE 2025 Pattern)
Case Study 1: Online Examination System
An online exam system accepts marks entered by teachers. Sometimes, teachers enter non-numeric values or zero by mistake.
Questions:
Which exception occurs if a teacher enters
"abc"instead of marks? ✔ValueErrorWhich exception occurs if marks are divided by zero? ✔
ZeroDivisionErrorWrite a Python code to handle both errors.
try: marks = int(input("Enter marks: ")) average = 100 / marks print(average) except ValueError: print("Marks must be numeric") except ZeroDivisionError: print("Marks cannot be zero")
Case Study 2: Banking Application
A banking app must ensure withdrawal amount is positive.
Question: How can this be enforced using Python?
amount = int(input("Enter withdrawal amount: "))
assert amount > 0, "Invalid withdrawal amount"
print("Transaction successful")
Case Study 3: File Upload System
A program reads a file uploaded by a user.
What exception occurs if file does not exist? ✔
FileNotFoundErrorWhy should
finallybe used?
✔ To ensure cleanup code always runs.
try:
f = open("upload.txt")
except FileNotFoundError:
print("Upload failed")
finally:
print("Process ended")