Exception Handling
What is an Exception?
An exception is an error that happens while a program is running and stops the normal flow
of the program.
Example:
● Dividing a number by zero
● Opening a file that does not exist
● Reading past the end of a file
If exceptions are not handled, the program crashes.
What is Exception Handling?
Exception handling means writing code that:
● Detects an error
● Shows a proper error message
● Prevents the program from stopping suddenly
This makes programs robust and safe to use.
Why Exception Handling is Important
Exceptions can occur because of:
● Programming mistakes
● Wrong user input
● Hardware problems (disk, printer, network)
Real programs must handle errors because:
● Users make mistakes
● Files or devices may fail
Basic Structure of Exception Handling
try:
# code that may cause an error
except:
# code that runs if an error occurs
Example 1: Division by Zero
Code
def division(firstNumber, secondNumber):
try:
answer = firstNumber // secondNumber
print("Answer:", answer)
except:
print("Divide by zero error")
division(12, 3)
division(10, 0)
Explanation
● try block contains risky code
● // is integer division
● If secondNumber is 0, an error occurs
● except block catches the error and prints a message
● Program does not crash
Example 2: Checking Input is an Integer (ACTIVITY 20N)
Code
try:
value = int(input("Enter an integer: "))
print("You entered:", value)
except:
print("Error: That is not an integer")
Explanation
● int() converts input to integer
● If user enters letters or symbols, error occurs
● except handles the error safely
File Handling with Exception Handling
Example 3: Opening a File Safely
Code
try:
file = open("[Link]", "r")
print([Link]())
[Link]()
except:
print("Error: File does not exist")
Explanation
● If [Link] does not exist, program crashes without handling
● try-except prevents crash
● Shows clear error message
Example 4: Handling Unexpected End of File (ACTIVITY
20O)
Code
try:
file = open("[Link]", "r")
while True:
line = [Link]()
if line == "":
break
print([Link]())
[Link]()
except:
print("Error while reading the file")
Explanation
● readline() reads one line at a time
● Empty string means end of file
● Loop stops safely
● Exception handling catches file errors
Using Specific Exceptions
Example 5: Specific Exception Types
try:
number = int(input("Enter a number: "))
result = 10 / number
print(result)
except ValueError:
print("Input is not an integer")
except ZeroDivisionError:
print("Cannot divide by zero")
Explanation
● ValueError: wrong input type
● ZeroDivisionError: division by zero
● More clear and professional error handling