handle multiple exceptions in python

How to Handle Multiple Exceptions in Python

Python allows you to handle different types of errors using different types of exceptions. But in a given code block, various kinds of errors are possible. It is important to be able to handle multiple exceptions in python. But sometimes, different exception types need he same code block to handle the error. This can lead to duplicate code. In such cases, it is advisable to group different exceptions together. In this article, we will learn different ways to handle multiple exceptions in python.


How to Handle Multiple Exceptions in Python

Here is a typical code block to catch an exception in Python.

try:
    # do something that may fail
except:
    # do this if ANYTHING goes wrong

In this case, the except statement catches all kinds of errors and runs the same code to handle each kind of exception. But this is a very general way to handle exceptions. You may need to handle different types of exceptions differently.

If there are multiple ways your code fails, you may add separate except statements for each kind of exception.

try:
    # do something that may fail
except OneTypeOfException:
    # do this if first type of exception occurs
except SecondTypeOfException:
    # do this if second type of exception occurs
...

Here is an example of above code structure.

try:
    client_obj.get_url(url)
except URLError:
    client_obj.remove_url(url)
except ValueError:
    client_obj.remove_url(url)
except SocketTimeout:
    client_obj.remove_url(url)   

In the above code block, if URLError Exception occurs the first except block will be executed. If ValueError type of exception occurs, the second except block will be executed. If SocketTimeout type of exception occurs, then the 3rd except block will be executed.

But this leads to unnecessary lines of code, as you can see above. Isn’t it better to simply group Exception types if they all lead to the same code block eventually? Here is how to group multiple exceptions into single line.


1. By Grouping Exception Classes

Basically to group multiple exception types together, list them in a comma-separated manner within round braces (). For example, (exceptionType1, exceptionType2,…). Here is the basic code block with such an except clause.

try:
    # do something that may fail
except (OneTypeOfException, SecondTypeofException):
    # do this if first or second type of exception occurs

In the above code block, we use group the different exception types using comma (,) operator, since they both will execute the same code block to handle the exception.

Here is an example where we rewrite the earlier example with grouping of Exception types URLError, ValueError, SocketTimeout

try:
    client_obj.get_url(url)
except (URLError, ValueError, SocketTimeout):
    client_obj.remove_url(url)

In case you want to handle one of the exceptions differently, you can put it in a separate except clause as shown below. In the following example, we have grouped URLError and ValueError but handled SocketTimeout separately.

try:
    client_obj.get_url(url)
except (URLError, ValueError):
    client_obj.remove_url(url)
except SocketTimeout:
    client_obj.handle_url_timeout(url)


Please note, you can also group multiple exceptions using the following syntax, by assigning it a variable, say e, for future reference.

# Python > 2
except (URLError, ValueError) as e:
# Python <= 2
except (URLError, ValueError), e:


2. By Using Common Base Exception Class

Exceptions are organized as hierarchy of classes with child classes inheriting from parent classes. So another way of grouping exceptions is to simply mention their common base class exception type. This works because exceptions are organized as a hierarchy where child exceptions inherit from parent Exception classes. Here is an example. Instead of using FileNotFoundError and PermissionError as shown below

try:
    f = open(filename)
except (FileNotFoundError, PermissionError):
    ...

you can directly use OSError because it is the base classe common to both FileNotFoundError and PermissionError.

try:
    f = open(filename)
except OSError:
    ...

But it is important to note, that in this case, the specific error conditions defined in child exception classes will not be available for error handling. But if you are sure that they won’t be needed and the base class is sufficient to handle the errors of both kinds of exceptions, then you can use it instead of using multiple child exception classes.

If you need to treat different exception types separately, you can use the errno attribute of exception object to separate exception into specific sub types, to investigate them further or handle them separately. Here is an example where we use errno attribute of exception object to determine the type of error.

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)

In this article, we have learnt a couple of different ways to group multiple exceptions in a single line of code in Python. Of them, the first method is more comprehensive and advisable, since it neatly groups different exception types making it easier to understand for developers, as to which types of exception handlers are being used and how.

Also read:

How to Make File Executable in Linux
How to Recursively Change Folder Permission in Linux
How to Get Size of Directory in Linux
How to Calculate Time Difference in Python
How to Measure Time Taken for Python Program

Leave a Reply

Your email address will not be published. Required fields are marked *