Python except multiple error

How to Catch Multiple Exceptions in Python

A well developed application must always be capable of handling unexpected events — such as exceptions — in a proper way. This is also important when it comes to debugging your source code during development, but also when it comes to inspecting the application logs when the application is up and running (eventually in production).

In today’s short tutorial we will showcase how one can handle multiple Exceptions in Python. We will also explore some new features in Python that can help you do so in a more intuitive and clean way. Let’s get started!

For Python < 3.11

Now let’s suppose that we have the following (fairly dumb) code snippet, that raises AttributeError , ValueError and TypeError .

def my_function(x): 
if x == 1:
raise AttributeError('Example AttributeError')
elif x == 2:
raise ValueError('Example ValueError')
elif x == 3:
raise TypeError('Example TypeError')
else:
print('Hello World')

And let’s also suppose that we want to to call the function my_function but at the same time, we also need to ensure that we handle any unexpected errors appropriately. To do so, we can use the try-except clauses.

Читайте также:  Php mysql одни знаки вопроса

But let’s assume that we want to perform a certain action if an AttributeError is being thrown and a different action when either of ValueError or TypeError are raised by my_function .

try: 
my_function(x)
except AttributeError:
# Do something
.
except (ValueError, TypeError):
# Do something else
.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple.

— Python Docs

If you are not planning to do anything special with any of the errors being raised (e.g. you just pass ) you can even use the suppress Context Manager as illustrated below:

Источник

How to Catch Multiple Exceptions in Python

How to Catch Multiple Exceptions in Python

When a program encounters an exception during execution, it is terminated if the exception is not handled. By handling multiple exceptions, a program can respond to different exceptions without terminating it.

In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

There are several approaches for handling multiple exceptions in Python, the most common of which are discussed below.

Using Same Code Block for Multiple Exceptions

With this approach, the same code block is executed if any of the listed exceptions occurs. Here’s an example:

try: name = 'Bob' name += 5 except (NameError, TypeError) as error: print(error) rollbar.report_exc_info()

In the above example, the code in the except block will be executed if any of the listed exceptions occurs. Running the above code raises a TypeError , which is handled by the code, producing the following output:

cannot concatenate 'str' and 'int' objects

Using Different Code Blocks for Multiple Exceptions

If some exceptions need to be handled differently, they can be placed in their own except clause:

try: name = 'Bob' name += 5 except NameError as ne: # Code to handle NameError print(ne) rollbar.report_exc_info() except TypeError as te: # Code to handle TypeError print(te) rollbar.report_exc_info()

In the above example, NameError and TypeError are two possible exceptions in the code, which are handled differently in their own except blocks.

Investigating Exceptions using If, Elif, Else Statements

Exceptions can also be checked using if-elif-else conditions, which can be useful if the exception needs to be investigated further:

import errno try: f = open('/opt/tmp/myfile.txt') except IOError as e: rollbar.report_exc_info() if e.errno == errno.ENOENT: print('File not found') elif e.errno == errno.EACCES: print('Permission denied') else: print e

Here, the variable e holds an instance of the raised IOError . The additional status code of the exception is checked in the if , elif and else blocks and the first match is executed:

Multiple Except Clauses Matching

There may be cases where a piece of code causes an exception that can match multiple except clauses:

try: f = open('/opt/tmp/myfile.txt') except EnvironmentError: rollbar.report_exc_info() print('Failed to open file') except IOError: rollbar.report_exc_info() print('File not found')

Since EnvironmentError is more general than IOError , it matches the exception in the code above. The EnvironmentError except clause is listed first, so the code within it gets executed, producing the following output:

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Sign Up Today!

How to Handle Unhashable Type List Exceptions in Python
How to Throw Exceptions in Python

«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»

Источник

How to catch multiple exceptions in Python?

In this tutorial, we’ll cover an important topic in Python programming: catching multiple exceptions in Python. With examples, I will show you, multiple exception handling in Python.

What is Exception Handling in Python?

In Python, an exception is an event that disrupts the normal execution of a program. This could be due to incorrect input, a server not responding, a file not being found, and so on. When these exceptions occur, Python halts the program and generates an error message.

We use try-except blocks to handle these exceptions and prevent our program from stopping abruptly. We’ll write the code that could potentially raise an exception in the try block and the code that handles the exception in the except block in Python.

Catch Multiple Exceptions in Python

In Python, we can catch multiple exceptions in a single except block. This is useful when you have a piece of code that might raise more than one type of exception and want to handle all of them similarly.

Here’s the basic syntax for catching multiple exceptions:

try: # code that may raise an exception except (ExceptionType1, ExceptionType2, ExceptionType3, . ): # code to handle the exception

Example: Handling multiple exceptions in Python

Let’s say you’re writing a Python program that reads a file and then performs a division operation with the data from the file. This code might raise several exceptions. The open() function might raise a FileNotFoundError if the file doesn’t exist, and the division operation might raise a ZeroDivisionError if you try to divide by zero.

Here’s how you could catch both exceptions in Python with a single except block:

try: file = open("myfile.txt", "r") number = int(file.read()) result = 100 / number except (FileNotFoundError, ZeroDivisionError): print("An error occurred")

In this code, if either a FileNotFoundError or a ZeroDivisionError is raised, the program will print “An error occurred” and continue executing the rest of the program.

However, if you want to execute different code for each exception, you would use separate except blocks:

try: file = open("myfile.txt", "r") number = int(file.read()) result = 100 / number except FileNotFoundError: print("The file was not found") except ZeroDivisionError: print("Cannot divide by zero")

n this example, if a FileNotFoundError is raised, the program will print “The file was not found”. If a ZeroDivisionError is raised, it will print “Cannot divide by zero”.

Another Example:

Let’s consider an example where we have a Python dictionary of user data, and we’re trying to perform some operations that could raise exceptions. The operations include accessing a key that might not exist (raising a KeyError ), and converting a string to an integer (which could raise a ValueError if the string does not represent a valid integer).

user_data = < "name": "John", "age": "25", "balance": "two thousand" # This should have been a numeric string. >try: # Accessing a non-existing key will raise a KeyError. email = user_data["email"] # Converting a non-numeric string to an integer will raise a ValueError. balance = int(user_data["balance"]) except (KeyError, ValueError) as e: print("An error occurred: ", str(e))

In this code, if the key “email” does not exist in the dictionary, a KeyError will be raised. Similarly, when trying to convert the string “two thousand” to an integer, a ValueError will be raised. Both of these exceptions are caught by the except block, and an error message is printed.

Check out the below screenshot for the output.

How to catch multiple exceptions in Python

Using as to access the Exception Object in Python

You can use the as keyword in your except block to access the exception object in Python. This allows you to print the error message associated with the exception, or access its other properties.

try: file = open("myfile.txt", "r") number = int(file.read()) result = 100 / number except (FileNotFoundError, ZeroDivisionError) as e: print("An error occurred: ", str(e))

In this code, if an exception is raised, the program will print “An error occurred: ” followed by the error message associated with the exception.

Conclusion

In this tutorial, we’ve discussed how to handle multiple exceptions in Python using the try-except blocks. This is a powerful tool that allows you to create robust programs that can handle unexpected errors in Python.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Оцените статью