Python Multiple Exception Handling (Try-Except)

Python Multiple Exception Handling
Share this blog with others!

In the previous blog, we learned about python decorators and generators. This time we are going to learn about Error Handling in Python. In this blog, we will learn about both the simple exception and Multiple Exception Handling in Python using Try, Except, and Finally Statement.

Why should we Handle the error?

The Answer is we handle the errors for the proper functioning of our program. Think you made a web server using python and didn’t handle the errors.

When the server goes to production any kind of error can occur and the web server will stop.

To make sure that the web server keeps running you will have to handle the errors.

Python Exception – Try and Except

There are many built-in Exceptions in Python. Let’s Learn some of the basic ones with the help of examples:

Zero Division Error

>>> 10 / 0

Traceback (most recent call last):
  File ".\main.py", line 1, in <module>
    10 / 0
ZeroDivisionError: division by zero

This is ZeroDivisionError, returned when we try to divide anything with zero.

Index Error

>>> lst = [1, 2, 3, 4] 
>>> print(lst[5])

Traceback (most recent call last):
  File ".\main.py", line 2, in <module>
    print(lst[5])
IndexError: list index out of range

This Error is returned when we try to access the index, not present in the array.

Let’s Now try to Handle Both the Errors:

try:
    a = 10/0
except ZeroDivisionError as e:
    print("Can't Divide by Zero -", e)
Can't Divide by Zero - division by zero

Handle the IndexError:

try:
    lst = [1, 2, 3, 4]
    print(lst[5])
except IndexError as e:
    print("Index out of Bound -", e)
Index out of Bound - list index out of range

Now let’s understand how the try and except block works in python.

First, the code inside the try block is run. If no error occurs, an exception is raised and the code inside the except block is executed, else the except block is skipped.

Learn Python List Comprehension and Inner Function.

Python Multiple Exception Handling
Image Source – Datacamp

Python Exception Error Type

Everything is an object in Python. The errors are also a class.

Example:

>>> print(IndexError.__class__)
>>> print(ZeroDivisionError.__class__)

<class 'type'>
<class 'type'>

Catch all Exceptions

We can also catch all exceptions in a single except block.

Example:

try:
    lst = [1, 2, 3, 4]
    a = 10 / 0
    print(lst[5])
except Exception:
    print("An Error Occured")
An Error Occured

Handle Multiple Exceptions in Python

Python also supports multiple exception handling.

A single except block can be used to catch many exceptions.

Example:

try:
    lst = [1, 2, 3, 4]
    a = 10 / 0
    print(lst[5])
except (ZeroDivisionError, IndexError) as e:
    print("An Error Occured -", e)
An Error Occured - division by zero
try:
    lst = [1, 2, 3, 4]
    print(lst[5])
    a = 10 / 0
except (ZeroDivisionError, IndexError) as e:
    print("An Error Occured -", e)
An Error Occured - list index out of range

Python Error Handling Finally Statement

Finally statement is always executed every time and after try and the except block.

try:
    lst = [1, 2, 3, 4]
    print(lst[5])
    a = 10 / 0
except (ZeroDivisionError, IndexError) as e:
    print(e)
finally:
    print("Error Handled")
list index out of range
Error Handled

Hope you like it!


Share this blog with others!

1 thought on “Python Multiple Exception Handling (Try-Except)”

  1. Two questions:

    1) wouldn’t it be better to stack the exceptions like >
    try:
    except IndexError as e1:
    except ZeroDivisionError as e2:
    finally:
    2) The real point to handle errors is to provide information to developers, users or invoke a specific function like logging hence the individual handling might be better.

Leave a Comment

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