Introduction
Step 1: Writing a Function that May Raise an Error
def divide(a, b):
return a / b
Step 2: Using Try and Except Blocks for Error Handling
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
print("Oops! You can't divide by zero.")
return None
Step 3: Testing the Error Handling Function
result1 = safe_divide(10, 2)
result2 = safe_divide(10, 0)
print("Result 1:", result1)
print("Result 2:", result2)
Output:
Result 1: 5.0
Oops! You can't divide by zero.
Result 2: None
Conclusion
Congratulations! You’ve learned the basics of error handling in Python. Using try and except blocks allows your program to handle unexpected situations gracefully. Keep exploring intermediate programming concepts and continue learning! 🚀