In one of my previous posts I brought up the idea of using try and except within python to handle errors but what if you want different responses for different errors? Well you’re in luck, you can have multiple exceptions for different errors and even have a default exception. This default exception must always be the last one listed and it will be executed if you receive an error and the other exceptions don’t specify it, each specific can only have one exception in the associated try and except
Ex:
try:
var = int(input(“Please input a positive integer and I’ll return the reciprocal: “))
result = 1 / var
print(var)
except ZeroDivisionError:
print(“Please enter a value other than zero”)
except ValueError:
print(“We are looking for a number”)
except:
print(“Are you trying to make things difficult”)
Result:
Please input a positive integer and I’ll return the reciprocal: 0
Please enter a value other than zero
Please input a positive integer and I’ll return the reciprocal: No
We are looking for a number
As you can see that is the power of exceptions, they can be very useful if you want to avoid your code spitting out confusing errors to your user and instead offer a more friendly explanation.