CLASS NOTES: EXCEPTION HANDLING & FILE
HANDLING
Subject: Computer Science – Class XII (CBSE)
Compiled by: Amit Bharadwaj (PGT Computer Science, SBV-Anand Vihar)
1. EXCEPTION HANDLING
Introduction: Exception is an unexpected error during execution. Exception handling
manages errors gracefully, preventing program crash.
Syntax Errors vs. Exceptions:
Aspect Syntax Error Exception
When? At compile-time At run-time
Example print "Hello" print(10/0)
Fix Must fix before execution Handle with try-except
Common Built-in Exceptions:
Exception When it occurs
ZeroDivisionError Division/modulo by zero
ValueError Wrong value of correct type (int('abc'))
FileNotFoundError File not found
EOFError End-of-file reached unexpectedly
ImportError Module not found
IndexError Index out of range
NameError Name not defined
TypeError Operation on wrong data type
Handling Exceptions: try-except-else-finally
Code Example:
try: num = int(input("Enter a number: ")) result = 100 / num except ValueError:
print("Enter a valid integer.") except ZeroDivisionError: print("Division by zero
not allowed.") except Exception as e: print("Unexpected error:", e) else:
print("Result =", result) finally: print("Program ended safely.")
2. FILE HANDLING
Types of Files:
Type Description Examples
Text Human-readable characters .txt, .py, .csv
Binary Stored in 0s and 1s (not human-readable) .dat, .jpg, .exe
CSV Special text file storing tabular data with commas .csv