Error Handling in Python
Error handling allows your program to deal with unexpected situations
without crashing. Python uses try, except,
else, and finally blocks to handle runtime errors.
What is an Exception?
An exception is an error that occurs during program execution. If not handled, the program will stop abruptly.
x = 10
y = 0
print(x / y) # ZeroDivisionError
Basic try / except
Use try and except to catch and handle errors.
try:
x = 10
y = 0
print(x / y)
except ZeroDivisionError:
print("Cannot divide by zero")
✔ Prevents program crash
✔ Handles runtime errors gracefully
✔ Improves user experience
Handling Multiple Exceptions
You can handle different types of exceptions separately.
try:
num = int("abc")
print(num)
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Division by zero")
Using else Block
The else block runs if no exception occurs.
try:
num = int("123")
except ValueError:
print("Conversion failed")
else:
print("Conversion successful:", num)
Using finally Block
The finally block always runs, whether an exception
occurs or not.
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
print("Closing operation completed")
📝 Practice:
Write a program that asks the user for two numbers and handles division errors using
Write a program that asks the user for two numbers and handles division errors using
try and except.