Python catch multiple exceptions [Practical Examples]

Introduction to Python catch multiple exceptions

In Python, try-except blocks are used to catch exceptions and process them. Sometimes we call a function that may throw multiple types of exceptions depending on the arguments, processing logic, etc. In this tutorial, we will learn about Python catching multiple exceptions. We will discuss how we can handle multiple exceptions that might occur during the execution of our Python program through various methods.

We will also learn how we can use multiple except blocks, python loop, and user-defined exceptions to handle multiple exceptions. At the same time, we will also learn how we can handle multiple exceptions just in one line using tuples by taking various examples. Moreover, we will also discuss how we can handle different types of exceptions by solving different examples. In a nutshell, this tutorial will contain all the necessary methods that you can use in order to handle multiple exceptions in the Python programming language.

Advertisement

 

Getting Started with Python catch multiple exceptions

As we have already discussed that try-except blocks in Python are used to handle different types of exceptions. You can learn more about the try and except block from the article on Python try and catch exceptions. In this section, our main focus will be to handle multiple exceptions using try and except blocks. The following is the simple syntax of the try and except block.

try:
    # statements inside try block
except:
    # statements inside except block

If an error occurs, in the try block then rather than terminating the program, the except block will be executed.

 

Method-1 Python catch multiple exceptions using python for loop

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 of Python 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:

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

 

Method-2 Python 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.

 

Example of Python catch different types of exceptions

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-3 Python catch multiple exceptions in one line

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.

Advertisement

 

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 Python catch multiple exceptions in one line

Now let us try to divide the number by zero and run our program.

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

Output:

The following error occurs:
division by zero

Notice that this error was also handled by the except block because ZeroDivisionError was mentioned in the tuple.

 

Method-4 Python catch all exceptions

Sometimes, we might don't know what kind of exception might occur. In such a scenario, it is better to handle all exceptions that might occur without specifying the type of error. The following is the simple syntax to handle all exceptions.

try:
    # Try block and statements
except Exception:
    # handle exceptions

Notice that here we did not have defined any type of exceptions, we have used the keyword exception which covers all types of exceptions that might occur during the execution of our program.

Advertisement

 

Example-1 Python catch all exceptions

Now let us see how the exception keyword works and handle all possible exceptions that might occur during the execution of our program. See the python program below:

# Python catch multiple exceptions
try:
    # defining variables
    a = 10
    b = 0
    c = 'sd'
    #dividing
    d = a/b
# except block
except Exception as e:
    # printing the error
    print("The following error occurs:")
    print(e)

Output:

The following error occurs:
division by zero

Notice that the exception part handled the zero exception and printed the error.

 

Example-2 Python catch all exceptions

Now let us try to come up with another exception. 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 Exception 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 the exception part handled another exception as well. This block will be able to handle all the built-in exceptions that might occur during the execution of the python program.

 

Method-5 Python catch user-defined exceptions

Sometimes, we might need to handle exceptions other than the built-in ones. In such a case, we have to define an exception on our own and then handle it, if it occurs. The following is the simple syntax of python's user-defined exception.

try:
    # if statement
    if conditions:
        # raise error
        raise Error1
    elif conditions:
        raise Error2
except Error1:
    # handle error 1
except Error2:
    # handle error 2

Notice that we have used if and else statements to define a user exception and then handle it in the except block.

 

Example of Python catch user-defined exception

Now let us see how we can catch a user-defined exception. See the following Python program.

# defining class
class Number(Exception):
    pass
# creating new class for small number error
class SmallNumberError(Number):
    pass
# Python catch multiple exceptions
try:
    # defining variables
    a= 10
    b=-1
    # condition for exceptions
    if b< 0:
        # raise an exception
        raise SmallNumberError
    else:
        print("No error")
# except block to handle exception
except SmallNumberError:
    print("The number is too small:")

Output:

The number is too small:

Notice that we have defined an exception on our own that if a number is smaller than 0 then raise an exception and we handle it in the except block.

 

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

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

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 either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X