Except multiple errors python

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.

Читайте также:  Apache httpclient java api

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.

Источник

Catch multiple exceptions in one line (except block)

But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:

try: # do something that may fail except IDontLikeYouException: # say please except YouAreBeingMeanException: # say please 

Is there any way that I can do something like this (since the action to take in both exceptions is to say please ):

try: # do something that may fail except IDontLikeYouException, YouAreBeingMeanException: # say please 
try: # do something that may fail except Exception, e: # say please 

So, my effort to catch the two distinct exceptions doesn’t exactly come through. Is there a way to do this?

6 Answers 6

An except clause may name multiple exceptions as a parenthesized tuple, for example

except (IDontLikeYouException, YouAreBeingMeanException) as e: pass 
except (IDontLikeYouException, YouAreBeingMeanException), e: pass 

Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as .

Is it possible to store desired exceptions in an iterable, and then catch the iterable? I’m trying to turn a list of warnings into errors using warnings.filterwarnings , and I don’t want to have to specify the list of warnings twice.

Читайте также:  Iterate array for php

I did try it. with a list , and it resulted in a TypeError . Looks like the errors must be in a tuple for catching to work as expected.

It was unclear whether the «parenthesized tuple» was merely syntactical or that a bona fide tuple was required. «Parenthesized» is misleading because you may create a tuple without parentheses elsewhere and then use it in the except line. It is only necessarily parenthesized if created in the except line.

@JosephBani That’s not true at all. In 2 + (x * 2) , (x * 2) is certainly not a tuple. Parentheses are a general grouping construct. The defining characteristic of a tuple is that it contains a comma — see the Python documentation: «Note that it is actually the comma which makes a tuple, not the parentheses.»

How do I catch multiple exceptions in one line (except block)

try: may_raise_specific_errors(): except (SpecificErrorOne, SpecificErrorTwo) as error: handle(error) # might log or have some other default behavior. 

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here’s an example of simple usage:

import sys try: mainstuff() except (KeyboardInterrupt, EOFError): # the parens are necessary sys.exit(0) 

I’m specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

You can assign the exception to a variable, ( e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys try: mainstuff() except (KeyboardInterrupt, EOFError) as err: print(err) print(err.args) sys.exit(0) 

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys try: mainstuff() except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+ print err print err.args sys.exit(0) 

If you see the comma name assignment in your codebase, and you’re using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try: do_something() except (IDontLikeYouException, YouAreBeingMeanException) as e: pass 

The try , except , pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress with suppress(IDontLikeYouException, YouAreBeingMeanException): do_something() 

So when you want to pass on certain exceptions, use suppress .

Читайте также:  Python docx insert paragraph

Источник

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.»

Источник

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