How to catch multiple exceptions in Python? [SOLVED]


Python

Author: Bashir Alam
Reviewer: Deepak Prasad

How do we catch exceptions in Python?

In Python, when an exception is raised, the normal flow of execution is interrupted, and the program jumps to the nearest enclosing exception handler. The mechanism is called "catching an exception".

When an exception is raised, the interpreter looks for an exception handler by searching the call stack. If the interpreter finds an exception handler that can handle the exception, the handler is executed. If the interpreter does not find an exception handler, it stops the execution of the program and prints an error message.

The try block is used to enclose the code that might raise an exception. The except block is used to define the exception handler. If an exception is raised in the try block, the interpreter checks the except block to see if it can handle the exception. If the exception type matches the exception specified in the except block, the code in the except block is executed, and the execution continues after the except block.

 

Can we catch multiple exceptions in Python?

You can catch different types of exceptions in separate except blocks. The try block can have multiple except blocks, each handling a different type of exception. The interpreter will execute the first except block whose exception matches the exception that was raised. If no matching except block is found, the interpreter will continue searching for an exception handler in the calling function or script.

 

Using different except blocks

You can catch multiple exceptions in different except blocks in Python. Here is an example:

try:
    # code that might raise an exception
except ExceptionType1:
    # code to handle ExceptionType1
except ExceptionType2:
    # code to handle ExceptionType2
except ExceptionType3:
    # code to handle ExceptionType3

In this example, if an exception of type ExceptionType1 is raised inside the try block, the code inside the first except block will be executed. If an exception of type ExceptionType2 is raised, the code inside the second except block will be executed, and so on.

In this the interpreter will execute only the first except block whose exception matches the exception that was raised. If the interpreter finds an exception handler, the execution will continue after the except block.

 

Catch all exceptions

It's also possible to catch all possible exceptions by using Exception instead of specific exception types.

try:
    # code that might raise an exception
except Exception as e:
    # code to handle the exception
    print(e) # e is the exception instance

 

Catch multiple exceptions inside single except block

You can catch multiple exceptions in one except block in Python using parentheses to specify the exception types. Here is an example syntax:

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

In this example, if any of the exceptions ExceptionType1, ExceptionType2, ExceptionType3 are raised inside the try block, the code inside the except block will be executed.

You can also use the as keyword to assign the exception instance to a variable:

try:
    # code that might raise an exception
except (ExceptionType1, ExceptionType2, ExceptionType3) as e:
    # code to handle the exception
    print(e) # e is the exception instance

For Example:

try:
    x = 1 / 0
except (ZeroDivisionError, TypeError) as e:
    print("Error:", e)

This will catch both ZeroDivisionError and TypeError and print the error message.

 

What are the Best Practices while handling exceptions in Python?

Here are some best practices for handling exceptions in Python:

  1. Use specific exception types when possible: It's best to catch specific exception types as much as possible, rather than using a general exception type like Exception. This makes your code more robust and less likely to accidentally catch an exception that you didn't expect.
  2. Handle exceptions at the appropriate level: Don't handle exceptions too low in the call stack. Handle exceptions as close as possible to where they occurred, while still providing a useful context.
  3. Don't ignore exceptions: If you catch an exception, make sure that you do something to handle it. Ignoring exceptions can lead to unexpected behavior and make it hard to debug your code.
  4. Use the finally block: The finally block is used to specify the code that will be executed regardless of whether an exception was raised or not. This can be useful for cleaning up resources, such as closing files or releasing memory.
  5. Be descriptive in exception handling: Use meaningful error messages and log exception details. This will make it easier to understand and fix the problem.
  6. Test your exception handling: Make sure that your exception handling code is working as intended by writing test cases that verify that exceptions are raised and handled correctly.
  7. Don't use exceptions for flow control: Exceptions are meant to handle exceptional cases, not to control the flow of your program. Use conditional statements and loops for that purpose.
  8. Avoid empty except block: Avoid using an empty except block, because it will catch all exceptions, including those that you didn't expect, and make it hard to debug your code.

 

Practical Examples to catch multiple exceptions

Method-1: Catch multiple exceptions in separate except block

Python for loop is used to loop through an iterable object (like a list, tuple, set, etc.) and perform the same action for each entry. We can use handle multiple exceptions that might occur while iterating an object. In such a case, we can use the try and catch block inside our Python for loop which will handle multiple exceptions. The following is the simple syntax.

for i in iterable:
    try:
        # try block statements
    except:
        # raise an erro

Notice that we have handled exceptions that might occur inside for loop.

 

Example-1: Catch multiple exceptions using for loop

Now let us take an example and see how we can use the python for loop to catch multiple exceptions. See the example below:

# iterable object
mylist = [-1, 2, 0, 4, 0]
# for loop
for i in mylist:
    # Python catch multiple exceptions
    try:
        # raise when divide by zero
        print("thedivision is:", 10/i)
    # this block will be executed if error occurs
    except:
        # raise an error
        print("Error occurs while dividing")

Output:

the division is: -10.0
the division is: 5.0
Error occurs while dividing
the division is: 2.5
Error occurs while dividing

Notice that the above program had raised two errors but was handled successfully using the except block.

 

Example-2: Catch different types of Exceptions

In python, there are many built-in exceptions for example ZeroDivisionError, IndexOutOfRange, TypeError, and many more. ZeroDivisionError occurs when a number is divided by zero and TypeError occurs when different data types are added or performed operations that cannot be performed. While IndexOutOfRange as the name suggests raises when the index is out of range. In this section, we will handle the given three types of errors. The following will be the simple syntax of handling the above different types of exceptions.

try:
    # try block statement
except ZeroDivisionError:
    # Raise exception
except IndexError:
    # raise exception
except TypeError:
    # raise exception

Depending on the type of exception that occurs in the try block, that specific except block will be executed to handle the exception.

Now let us see how we handle different types of exceptions that might occur during the execution of the try block. See the following Python program.

# Python catch multiple exceptions
try:
    # defining variables
    a = 10
    b= 0
    c = "abc"
    # adding the variables
    d =a+c
# Zerodivision error
except ZeroDivisionError:
    # printing error
    print("Zero Division Error occurs")
# index error
except IndexError:
    # printing
    print("Index error occurs")
# type error
except TypeError:
    # printing
    print("Type error occurs")

Output:

Type error occurs

Type error occurs because in Python we cannot directly add string and integer data types together. So because the type error was thrown by the try block, that is why only the TypeError except block was executed.

 

Method-2: Catch multiple exceptions in single except block

Instead of writing different types of exceptions in different except blocks, we can write them in one line using a tuple.  A Tuple is nothing, just a collection of Python objects separated by commas. We write all the exception types that might occur in a tuple and use one except block. See the following syntax of multiple exceptions in one line.

try:
    # Try statements
except(TypeError, SyntaxError, ValueError, ...)as e:
    # exceptions

Notice that we have condensed all the exceptions in just one line using by writing then inside a typle.

 

Example-1: Python catch multiple exceptions in one line

Now let us see how we can handle multiple exceptions in just one line. See the python program below:

# Python catch multiple exceptions
try:
    # defining variables
    a = 10
    b = 0
    c = 'sd'
    # adding 
    d = a+c
# except block
except(TypeError, SyntaxError, ValueError)as e:
    # printing the error
    print("The following error occurs:")
    print(e)

Output:

The following error occurs:
unsupported operand type(s) for +: 'int' and 'str'

Notice that the type error occurs and was handled in the except block.

 

Example-2: Handling multiple exceptions in single except block

Let's go one step ahead and handle some more exceptions in single except block.

import json
try:
    # code that might raise an exception
    x = 1 / "a" # will raise TypeError
    y = open("file_not_exist.txt") # will raise FileNotFoundError
    z = "a" + None # will raise TypeError
    data = json.loads("{'invalid': json}") # will raise json.decoder.JSONDecodeError

except (TypeError, FileNotFoundError, json.decoder.JSONDecodeError) as e:
    print("Error:", e)
    x, y, z, data = None, None, None, None

# continue processing data
print("x:", x)
print("y:", y)
print("z:", z)
print("data:", data)

In this example, the try block contains 4 operations that will raise different types of exceptions:

  • The division of 1 by "a" will raise a TypeError exception because it's not possible to divide an integer by a string.
  • The open("file_not_exist.txt") will raise a FileNotFoundError exception because the file does not exist.
  • The concatenation of "a" and None will raise a TypeError exception because it's not possible to concatenate a string and None.
  • The json.loads("{'invalid': json}") will raise a json.decoder.JSONDecodeError exception because the json string is not valid.
  • The except block is set to catch all three exception types: TypeError, FileNotFoundError, json.decoder.JSONDecodeError . If an exception is raised, the program will print an error message and set all variables x, y, z, data to None.

 

Summary

In Python, we use the try and except blocks to catch and handle any kind of exceptions and errors that might occur during the execution of our program. In this tutorial, we have learned about python catch multiple exceptions by using various methods. We have discussed five different ways of handling multiple exceptions by taking various examples. We covered how we can handle exceptions using except blocks, different types of exceptions and how we can handle all types of exceptions in just one line. Moreover, we also discussed how we can define our own exception and handle it. To summarize, this tutorial contains all the necessary methods that are used to handle multiple exceptions in different scenarios

 

Further Reading

Python try and except
Python exception handling
Python built-in Exceptions
Catch multiple exceptions in one line (except block)

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment