π― Lesson Objective
To understand how to handle errors in Python gracefully using exceptions, preventing program crashes and improving reliability.
π§© 1. What Is an Exception?
An exception is an error that occurs during program execution.
Examples: dividing by zero, file not found, invalid input, etc.
β Example:
num = 10
print(num / 0) # This will raise ZeroDivisionError
Output:
ZeroDivisionError: division by zero
βοΈ 2. Try and Except Block
Use try to test code and except to handle exceptions.
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Enter an integer.")
Behavior:
- If input is 0 β prints “Cannot divide by zero!”
- If input is not a number β prints “Invalid input! Enter an integer.”
π 3. Handling Multiple Exceptions
You can handle multiple exceptions in one block.
try:
x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
result = x / y
except (ZeroDivisionError, ValueError) as e:
print("Error occurred:", e)
else:
print("Result is:", result)
finally:
print("Execution finished.")
π§° 4. Common Built-in Exceptions
| Exception | Cause | Example |
|---|---|---|
ZeroDivisionError | Division by zero | 10/0 |
ValueError | Invalid value | int("abc") |
FileNotFoundError | File doesnβt exist | open("nofile.txt") |
TypeError | Wrong data type | "5" + 5 |
IndexError | Invalid index | arr[10] |
KeyError | Key not found in dict | dict["x"] |
π 5. Try, Except, Else, Finally
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful, result:", result)
finally:
print("End of program")
try: code that may raise an exceptionexcept: code to handle exceptionelse: runs if no exception occursfinally: always runs
π§© 6. Raising Exceptions
You can raise exceptions intentionally using raise.
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("Age must be 18 or above.")
π 7. Real-Life Example β Safe Input
while True:
try:
num = int(input("Enter a positive number: "))
if num < 0:
raise ValueError("Number cannot be negative")
break
except ValueError as e:
print("Error:", e)
print("You entered:", num)

Leave a Reply