Exception Handling – Full Notes with
Examples (CBSE Class 12)
1 Types of Errors
1️⃣
🔹 Compile-Time Errors
Errors caused by syntax rule violations.
Detected during code compilation.
Example:
print("Hello"
# Missing closing bracket → SyntaxError
🔹 Run-Time Errors
Occur during program execution due to unexpected input or situations.
Example:
a = 5 / 0 # ZeroDivisionError
2️⃣What is an Exception?
An exception is an unexpected error that occurs at runtime, disrupting normal program
flow.
Examples:
- Dividing by zero
- Accessing a list index that doesn’t exist
- File not found
- Converting string to integer
3️⃣Basic Exception Handling
Syntax:
try:
# Risky code
except ExceptionType:
# Handling code
Example:
try:
num = int(input("Enter a number: "))
print("Result:", 100 / num)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input! Please enter an integer.")
4️⃣Common Built-in Exceptions
ZeroDivisionError – Dividing by 0
ValueError – Converting invalid input
IndexError – Accessing invalid list index
NameError – Variable not defined
TypeError – Operation on wrong data type
IOError – File read/write errors
KeyError – Accessing missing dict key
ImportError – Module not found
Example:
try:
lst = [1, 2, 3]
print(lst[5]) # IndexError
except IndexError:
print("Index out of range.")
5️⃣Handling Multiple Exceptions
Syntax:
try:
# Risky code
except ValueError:
# Handle ValueError
except ZeroDivisionError:
# Handle ZeroDivisionError
Example:
try:
a = int(input("Enter number: "))
b = int(input("Enter divisor: "))
print("Result:", a / b)
except ValueError:
print("Please enter valid integers.")
except ZeroDivisionError:
print("You cannot divide by zero.")
6️⃣Using else and finally
Syntax:
try:
# code
except:
# error handling
else:
# runs if no error
finally:
# always runs
Example:
try:
num = int(input("Enter a number: "))
except ValueError:
print("That's not a number.")
else:
print("Square:", num * num)
finally:
print("Execution complete.")
7️⃣Accessing Exception Object
Syntax:
except ExceptionType as e:
print(e)
Example:
try:
x=1/0
except ZeroDivisionError as e:
print("Error occurred:", e)
8️⃣Raising / Forcing an Exception
Syntax:
raise ExceptionType("Your message")
Example:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative.")
else:
print("Your age is", age)
9️⃣Practice Programs
🔸 Program 1: Handle Invalid Input & Division by Zero
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Quotient:", a / b)
except ValueError:
print("Invalid input.")
except ZeroDivisionError:
print("Cannot divide by zero.")
🔸 Program 2: File Handling Error
try:
f = open("[Link]", "r")
print([Link]())
[Link]()
except FileNotFoundError:
print("File not found.")
🔸 Program 3: Average of List Input
try:
nums = input("Enter numbers separated by space: ").split()
nums = [int(x) for x in nums]
avg = sum(nums) / len(nums)
print("Average:", avg)
except ZeroDivisionError:
print("Empty list.")
except ValueError:
print("Enter valid integers.")
🔸 Program 4: Force Custom Exception
password = input("Enter password: ")
if len(password) < 6:
raise Exception("Password too short!")
else:
print("Password accepted.")