In the previous section, we explored the basic try...except block, which acts like a net catching any error that might occur within the try block. While this is useful, sometimes you want to be more precise about what you're catching. Imagine you're baking a cake and you expect one ingredient might be missing (like flour), but you also know another problem could arise (like the oven malfunctioning). You'd want to handle these two potential issues differently. Python allows you to do just that by specifying the exact type of exception you want to catch.
This is achieved by placing the exception type immediately after the except keyword. Python has a rich hierarchy of built-in exceptions, each representing a different kind of error. By catching specific exceptions, your code becomes more robust and your error handling more targeted. This makes debugging easier because you know precisely which error you're addressing.
try:
# Code that might raise an error
number = int(input("Enter a number: "))
result = 10 / number
print(f"The result is: {result}")
except ValueError:
print("Invalid input. Please enter a whole number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")In this example, we've introduced two specific exception types: ValueError and ZeroDivisionError. The ValueError will be caught if the user enters something that cannot be converted to an integer (like text). The ZeroDivisionError will be caught if the user enters '0', preventing a division by zero. The final except Exception as e: acts as a general fallback to catch any other unforeseen errors, which is a good practice to include.
You can even catch multiple exceptions in a single except block by listing them within parentheses. This is useful when several different error types should be handled in the same way.
try:
# Code that might raise an error
value = int(input("Enter a number: "))
print(10 / value)
except (ValueError, ZeroDivisionError):
print("Invalid input or division by zero. Please try again.")This approach simplifies your code when the remedial action is identical for different error conditions. Remember, the order of your except blocks matters. Python will execute the first except block that matches the raised exception. Therefore, it's generally best to put more specific exception types before more general ones.