You can build on the previous example to handle more than one exception in a try except block by adding more than one except statement:
try:
dividend = int(input("Please enter the number to be divided: "))
divisor = int(input("Please enter the divisor: "))
result = dividend / divisor
print(f"The result of {dividend} divided by {divisor} is {result}")
except ZeroDivisionError:
print("My most sincere apologies, but you can't divide by zero.")
except ValueError:
print("I am once again asking you to use only digits in your input.")
The above example will now handle a ZeroDivisionError and a ValueError. The second one will get raised in case the user doesn't input something that can be converted to an integer.
Catching Multiple Exceptions
You can add as many additional except statements as you want to. If you want to make sure that your program doesn't quit on your users for sure, but you're running out of ideas of which exceptions might occur, you can add a final plain except in order to catch any other exception:
try:
dividend = int(input("Please enter the number to be divided: "))
divisor = int(input("Please enter the divisor: "))
result = dividend / divisor
print(f"The result of {dividend} divided by {divisor} is {result}")
except ZeroDivisionError:
print("My most sincere apologies, but you can't divide by zero.")
except ValueError:
print("I am once again asking you to use only digits in your input.")
except:
print("Please remain calm...")
Stay cautious and only use the catch-all except sparingly. The final except statement in this example code will handle any exception that gets raised unless it's one of the two preceding ones that have already been caught. Using it like this won't keep any information about which exception got raised, either. This might leave you guessing and can make it hard to track down tricky bugs.
Accessing Exception Information
As you might have guessed, any exception in Python is an object. Even more precisely, they all inherit from a built-in class called BaseException. That's why all exceptions have a similar interface and allow you to access some of their attributes that can help with more detailed debugging.
Info: Most exceptions that you'll want to catch in a catch-all except statement are further subclasses of the Exception class, which is a subclass of BaseException. Because it's a much more common sight than explicitly naming BaseException, you'll get to know how to catch all subclasses of an Exception object instead of the BaseException object. If you want to learn more, check out the links at the bottom of this lesson.
To get more information about an Exception object, you can assign a variable to it when you catch it. So far, you haven't assigned a variable to any of the caught Exception objects. Below, you'll change that for the final catch-all exception:
try:
dividend = int(input("Please enter the number to be divided: "))
divisor = int(input("Please enter the divisor: "))
result = dividend / divisor
print(f"The result of {dividend} divided by {divisor} is {result}")
except ZeroDivisionError:
print("My most sincere apologies, but you can't divide by zero.")
except ValueError:
print("I am once again asking you to use only digits in your input.")
except Exception as e:
print(f"I humbly inform you that {e} has occurred.")
List of Additional Information
With just a slight change in your code, you've now got access to more information about whatever exception has occurred:
- By catching the
Exceptionclass, you'll still catch any built-in Python exceptions since they all inherit from that class. - Then you use the assignment keyword
asto assign whateverExceptionobject got caught to the variablee. This is just a variable name, so you can name it however you want to. - Finally, you can now use the variable
eas a reference to the caughtExceptionobject inside theexceptblock and print out more information on it.
In this case, you're only printing the default output of the Exception object, or more precisely, the return value of its __str__(). But there's more to Exception objects, and you can decide which output will be most helpful for you to aid with debugging the issue that came up. You'll dive deeper into this when designing your own custom exception object in a few lessons from here.
In the next lesson, you'll learn some other possible constructs that extend on the try except structure you got to know up to now.
Additional Resources
- Python Documentation: Built-in Exceptions
- Real Python: Python Exceptions: An Introduction
Summary: How to Handle Multiple Python Exceptions
- You can string as many explicit
exceptstatements after one another as you want to. - Exceptions in Python are objects. All of them are subclasses of
BaseException, and the most common ones you want to catch are subclasses ofException. - By assigning the exception object to a variable, you can access the caught exception object and its attributes inside the
exceptblock.