In this tutorial, you’ll learn various techniques to catch multiple exceptions with Python. To begin with, you’ll review Python’s exception handling mechanism before diving deeper and learning how to identify what you’ve caught, sometimes ignore what you’ve caught, and even catch lots of exceptions.
Python raises an exception when your code encounters an occasional but not unexpected error. For example, this will occur if you try to read a missing file. Because you’re aware that such exceptions may occur, you should write code to deal with, or handle, them. In contrast, a bug happens when your code does something illogical, like a miscalculation. Bugs should be fixed, not handled. This is why debugging your code is important.
When your Python program encounters an error and raises an exception, your code will probably crash, but not before providing a message within a traceback indicating what the problem is:
>>> 12 / "five"
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Here, you’ve tried to divide a number by a string. Python can’t do this, so it raises a TypeError
exception. It then shows a traceback reminding you that the division operator doesn’t work with strings.
To allow you to take action when an error occurs, you implement exception handling by writing code to catch and deal with exceptions. Better this than your code crashing and scaring your user. To handle exceptions, you use the try
statement. This allows you to monitor code for exceptions and take action should they occur.
Most try
statements use try
… except
blocks as follows:
-
The
try
block contains the code that you wish to monitor for exceptions. Any exceptions raised withintry
will be eligible for handling. -
One or more
except
blocks then followtry
. These are where you define the code that will run when exceptions occur. In your code, any raised exceptions trigger the associatedexcept
clause. Note that where you have multipleexcept
clauses, your program will run only the first one that triggers and then ignore the rest.
To learn how this works, you write a try
block to monitor three lines of code. You include two except
blocks, one each for ValueError
and ZeroDivisionError
exceptions, to handle them should they occur:
# handler_statement.py
try:
first = float(input("What is your first number? "))
second = float(input("What is your second number? "))
print(f"{first} divided by {second} is {first / second}")
except ValueError:
print("You must enter a number")
except ZeroDivisionError:
print("You can't divide by zero")
The code that you’re monitoring asks the user to enter both numbers and then prints the division. You’ll cause a ValueError
if you don’t enter a number in the first two lines of code. When the float()
function tries to convert your input into a float
, a ValueError
occurs if this isn’t possible. A ZeroDivisionError
occurs if you enter 0
as the second number. When the print()
function attempts to divide by zero, you get a ZeroDivisionError
.
Having written the above code, you then test each of the control flows. To do this, you first provide perfectly valid data, then provide a string
for the second number, and finally provide a 0
for the second number:
$ python handler_statement.py
What is your first number? 10
What is your second number? 5
10.0 divided by 5.0 is 2.0
$ python handler_statement.py
What is your first number? 10
What is your second number? "five"
You must enter a number
$ python handler_statement.py
What is your first number? 10
What is your second number? 0
You can't divide by zero
The good news is that your code never crashes. This is because your code has successfully handled the exceptions.
First, you provided acceptable data. When you look at the output, you can see that the program flows only through try
. You haven’t invoked any of the except
clauses because Python hasn’t raised any exceptions.
You then cause a ValueError
by entering a string. This happens because the float()
function can’t convert your "five"
into a float
. Your program flow now becomes try
then except ValueError
. Despite raising a ValueError
, your code has handled it gracefully. Your users will no longer experience a worrying crash.
In your final test run, you try to divide by 0
. This time, you cause a ZeroDivisionError
because Python doesn’t like your enthusiasm for Riemann spheres and infinity. This time, the program flow is try
then except ZeroDivisionError
. Again, your code has handled your exception gracefully. Most of your users will be happy with this, though the mathematicians may be disappointed.
After the error handling is complete, your program’s flow would usually continue with any code beyond the try
statement. In this case, there’s none, so the program simply ends.
As an exercise, you might like to try entering a string as the first input and a number as the second. Can you predict what will happen before you try it out?
Note: Your code catches only ZeroDivisionError
or ValueError
exceptions. Should any others be raised, it’ll crash as before. You could get around this by creating a final except Exception
clause to catch all other exceptions. However, this is bad practice because you might catch exceptions that you didn’t anticipate. It’s better to catch exceptions explicitly and customize your handling of them.
Up to this point, you’ve reviewed how to catch exceptions individually using the try
statement. In the remainder of this tutorial, you’ll learn about ways that you can catch multiple exceptions. Time to dive a bit deeper.
Get Your Code: Click here to download the sample code that shows you how to catch multiple exceptions in Python.
How to Catch One of Several Possible Python Exceptions
Catching individual exceptions in separate except
clauses is the way to go if you need to perform different handling actions on the different exceptions being caught. If you find that you’re performing the same actions in response to different exceptions, then you can produce simpler, more readable code by handling multiple exceptions in a single except
clause. To do this, you specify the exceptions as a tuple within the except
statement.
Suppose you now like the idea of your earlier code being able to handle both exceptions in a single line. To do this, you decide to rewrite your code as follows:
Read the full article at https://realpython.com/python-catch-multiple-exceptions/ »
[ Improve Your Python With ? Python Tricks ? – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses
Email:
public1989two@gmail.com
www.itsec.hk
www.itsec.vip
www.itseceu.uk
Leave a Reply