In this lesson, you will learn how to write more resilient code by assigning custom recovery strategies to different types of runtime errors.
When your program encounters a problem, it raises an exception. While a generic except: block can catch everything, it is often a "bad practice" because it masks bugs you didn't anticipate. Instead, Python allows you to write multiple except blocks, each targeting a specific class of error. This way, if a file fails to open, you can log a specific message, but if a mathematical calculation fails, you can perform a completely different fallback action.
Consider a situation where you are reading a configuration file and performing a division:
try:
with open("config.txt", "r") as f:
data = int(f.read())
result = 100 / data
except FileNotFoundError:
print("Error: The config file is missing. Using default settings.")
except ValueError:
print("Error: The file contains invalid data. Ensure it's a number.")
except ZeroDivisionError:
print("Error: Cannot divide by zero. Check your config file values.")
By stacking these blocks, Python checks them from top to bottom. If a FileNotFoundError occurs, the first block executes and the rest are skipped. If a ZeroDivisionError occurs, the program skips the file and conversion blocks, jumping straight to the appropriate handler.
This approach is powerful because it treats different failures as distinct scenarios rather than just "program crashes." You can inform the user exactly what went wrong—like telling them their file is missing versus telling them their math is impossible—making your application much easier to troubleshoot. Always remember to put more specific exceptions (like ZeroDivisionError) before more general ones (like Exception), though ideally, you should avoid catching the base Exception class entirely to keep your error handling precise.
Key Takeaway: By catching specific exception types individually, you can provide tailored recovery logic that makes your programs more reliable and easier to debug.