Multiple Exception Handling in Python
Last Updated :
12 Jun, 2019
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages.
If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in the code given below :
Code #1 :
Python3 1==
try:
client_obj.get_url(url)
except (URLError, ValueError, SocketTimeout):
client_obj.remove_url(url)
The
remove_url()
method will be called if any of the listed exceptions occurs. If, on the other hand, if one of the exceptions has to be handled differently, then put it into its own except clause as shown in the code given below :
Code #2 :
Python3 1==
try:
client_obj.get_url(url)
except (URLError, ValueError):
client_obj.remove_url(url)
except SocketTimeout:
client_obj.handle_url_timeout(url)
Many exceptions are grouped into an inheritance hierarchy. For such exceptions, all of the exceptions can be caught by simply specifying a base class. For example, instead of writing code as shown in the code given below -
Code #3 :
Python3 1==
try:
f = open(filename)
except (FileNotFoundError, PermissionError):
...
Except statement can be re-written as in the code given below. This works because
OSError
is a base class that’s common to both the
FileNotFoundError
and
PermissionError exceptions.
Code #4 :
Python3 1==
try:
f = open(filename)
except OSError:
...
Although it’s not specific to handle multiple exceptions per
se, it is worth noting that one can get a handle to the thrown exception using them as a keyword as shown in the code given below.
Code #5 :
Python3 1==
try:
f = open(filename)
except OSError as e:
if e.errno == errno.ENOENT:
logger.error('File not found')
elif e.errno == errno.EACCES:
logger.error('Permission denied')
else:
logger.error('Unexpected error: % d', e.errno)
The
e variable holds an instance of the raised OSError. This is useful if the exception has to be invested further, such as processing it based on the value of the additional status code. The except clauses are checked in the order listed and the first match executes.
Code #6 : Create situations where multiple except clauses might match
Python3 1==
Output :
Traceback (most recent call last):
File "", line 1, in
FileNotFoundError: [Errno 2] No such file or directory: 'miss
Python3 1==
try:
f = open('missing')
except OSError:
print('It failed')
except FileNotFoundError:
print('File not found')
Output :
Failed
Here the except
FileNotFoundError
clause doesn’t execute because the
OSError
is more general, matches the FileNotFoundError exception, and was listed first.
Similar Reads
Handling NameError Exception in Python Prerequisites: Python Exception HandlingThere are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are :1. Misspelled built-in functions
2 min read
Python Exception Handling Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example:Handl
7 min read
How to Catch Multiple Exceptions in One Line in Python? There might be cases when we need to have exceptions in a single line. In this article, we will learn about how we can have multiple exceptions in a single line. We use this method to make code more readable and less complex. Also, it will help us follow the DRY (Don't repeat code) code method.Gener
2 min read
How to Call Multiple Functions in Python In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, weâll explore various ways we can call multiple functions in Python.The most straightforward way to call multiple functions is by executing them one after a
3 min read
How to handle KeyError Exception in Python In this article, we will learn how to handle KeyError exceptions in Python programming language. What are Exceptions?It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.Exceptions are runtime errors because, th
3 min read