Exception Handling in Python
Exception handling helps prevent program crashes by managing runtime errors in a controlled way.
💡 An exception is an error that occurs during program execution.
Example of an Error
print(10 / 0)
❌ This causes a ZeroDivisionError.
Using try and except
Use try to test code and except to handle errors.
try:
print(10 / 0)
except:
print("Cannot divide by zero")
Handling Multiple Exceptions
try:
num = int(input("Enter number: "))
print(10 / num)
except ValueError:
print("Please enter a valid number")
except ZeroDivisionError:
print("Division by zero is not allowed")
Using else Block
try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("You entered:", x)
Using finally Block
The finally block always executes, whether an error occurs or not.
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found")
finally:
print("Program ended")
Practice Exercises
- Handle division by zero using try-except
- Handle invalid user input
- Use finally block to print a message