2nd PUC Computer Science - NCERT Notes
Topic: Exception Handling in Python
* What is an Exception?
An exception is a runtime error that occurs when a program violates Python's rules or logic (e.g.,
dividing by zero, accessing an invalid index, etc.).
* Need for Exception Handling
1. To avoid program crashes
2. To detect and fix runtime errors
3. To maintain program flow
4. To provide user-friendly error messages
* Common Python Exceptions
ZeroDivisionError - Dividing a number by zero
IndexError - Accessing an invalid list index
ValueError - Using the wrong value type
FileNotFoundError - Opening a non-existent file
TypeError - Using incompatible data types
* Exception Handling Syntax in Python
try:
# Code that may cause an error
except ExceptionType:
# Code to handle the error
else:
# (Optional) Runs if no exception occurs
finally:
# (Optional) Runs no matter what
* Example 1: Handling ZeroDivisionError
try:
a = 10
b=0
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Output:
Error: Cannot divide by zero.
* Example 2: Handling Multiple Exceptions
try:
num = int(input("Enter a number: "))
print("Result:", 10 / num)
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
* Example 3: Catching the Exception Object
try:
a = int("abc")
except ValueError as e:
print("Caught an exception:", e)
Output:
Caught an exception: invalid literal for int() with base 10: 'abc'
* Example 4: Using Finally Block
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Execution of finally block.")
Output:
File not found.
Execution of finally block.
* Keywords Summary
try - Block where exception may occur
except - Handles the specific exception
else - Runs if no exception occurs (optional)
finally - Always runs (used for cleanup, optional)
* Importance in Real Life
- Banking applications: Handle invalid account operations.
- Web applications: Prevent crash on incorrect input.
- File handling: Manage missing or corrupt files.