Handling Multiple Exceptions in Python
In this tutorial, we will understand how to catching and handling multiple exceptions in Python with the help of various examples.
In a single piece of code, there might occur different types of exceptions. In Python, a single try block can also have multiple except blocks to specify handlers for different exceptions.
When statements in a single try block generate multiple exceptions, we might require multiple except blocks to handle different types of exceptions. This mechanism is called multi-except block, and the process is called multiple exception handling in Python.
However, only one of the except block (handler) will be executed for a single exception occurrence within a try block. Each except block is capable of catching a different exception. That is, each except block must contain a different exception handler.
Syntax to Handle Multiple Exceptions
The syntax for handling multiple exceptions using a single try with more than one except block in Python is as follows:
try:
# Code that might raise exceptions
# ...
except ExceptionType1:
# Code to handle ExceptionType1
# ...
except ExceptionType2:
# Code to handle ExceptionType2
# ...
except ExceptionTypeN:
# Code to handle ExceptionTypeN
# ...
In the above syntax, ExceptionType1, ExceptionType2,. . . . , ExceptionTypeN represents the specific type of exceptions we want to handle separately. When an exception occurs in the try block, Python checks each except block sequentially to find the one that matches the raised exception.
If the first except block matches for the raised exception inside the try block, the remaining except blocks will be skipped and continue for further execution of code that is outside the try-except block in the program. In case the specific type of exception thrown does not match with the first except block, the second except block will check, and so on.
At a time, only one exception occurs and only one corresponding except block executes. We must arrange all except blocks in such a way that more specific exception types come before more general ones (from subclass to superclass). This ensures that the interpreter catches the most specific exceptions first before moving on to more general exceptions. Thus, multiple except blocks allow us to handle different exceptions in different ways for the same try block.
The diagrammatic representation of working of a single try block with multiple except blocks for handling multiple exceptions in Python is in the below figure.
Here’s an example demonstrating the arrangement of except blocks from more specific exception types to more general ones, demonstrating how Python handles exceptions:
Example 1:
try:
num_list = [10, 20, 30]
print(num_list[4]) # Trying to access an index that doesn't exist
except IndexError:
print("IndexError occurred: Index out of range")
except Exception:
print("Exception occurred")
Output:
IndexError occurred: Index out of range
In this example, we have defined a try block in which we are endeavoring to access an index that doesn’t exist in the num_list. The first except block catches the IndexError, which specifically handles index-related issues. The second except block, catching the more general Exception, acts as a fallback in case any other unforeseen exception occurs.
Python matches the raised IndexError exception with the first except block, executes the code within it, and then moves on with the program. This arrangement ensures that the specific exceptions are handled before more general ones, allowing for precise and targeted exception handling.
Python Multiple Exceptions Handling Program
Let us take some important example programs based on the multiple exceptions handling for the best practice in Python.
Example 2:
class MultipleExceptionHandling:
def funct(self):
x = int(input("Enter your first number: "))
y = int(input("Enter your second number: "))
try:
print(x / y) # This statement will execute if y is not zero.
print("20" + 20)
except(TypeError):
print("Type exception")
except(ZeroDivisionError):
print("A number cannot be divided by 0, Illegal operation in Python")
# Outside the class definition.
# Creating an object of the class.
obj = MultipleExceptionHandling()
obj.funct() # calling method
Output:
First run:
Enter your first number: 20
Enter your second number: 0
A number cannot be divided by 0, illegal operation in Python
Second run:
Enter your first number: 40
Enter your second number: 10
4.0
Type exception
Example 3:
class MultipleExceptionHandling:
def func(self):
try:
# Perform some operations that might raise exceptions
result = 10 / 0 # ZeroDivisionError: division by zero
num_list = [1, 2, 3]
print(num_list[4]) # IndexError: list index out of range
except ZeroDivisionError:
print("ZeroDivisionError occurred: Division by zero")
except IndexError:
print("IndexError occurred: Index out of range")
except Exception:
print("An exception occurred")
# Outside the class definition.
# Creating an object of the class.
obj = MultipleExceptionHandling()
obj.func() # calling method
Output:
ZeroDivisionError occurred: Division by zero
In this example, we have defined a try block in which we attempt two operations that could raise specific exceptions: dividing by zero (ZeroDivisionError) and accessing an index that doesn’t exist in a list (IndexError). Then, we have defined two separate except blocks to handle each specific exception type, providing custom error messages for each type of exception. The last except block with Exception catches any other exception and prints a general message.
Multiple Exception Handling with One Except Block
We can also handle more than one exception with a single except block or clause as a parenthesized tuple. The general syntax is as follows:
try:
statement(s)
except(ExceptionType1, ExceptionType2, . . . . , ExceptionTypeN):
statement(s)
Example 4:
try:
num = float(input("Enter a number: "))
result = 20 / num
print("Result: ", result)
except(ValueError, ZeroDivisionError):
print("Your input is not a value, you should enter either an int or float number.")
print("Result is infinity because you have entered zero value.")
Output:
First run:
Enter a number: Good
Your input is not a value, you should enter either an int or float number.
Result is infinity because you have entered zero value.
Second run:
Enter a number: 10
Result: 2.0
We can also handle the same exception in two separate except clauses, as given below:
Example 5:
try:
num = float(input("Enter a number: "))
result = 20 / num
print("Result: ", result)
except(ValueError):
print("Your input is not a value, you should enter either an int or float number.")
except(ZeroDivisionError):
print("Result is infinity because you have entered zero value.")
Output:
First run:
Enter a number: very good
Your input is not a value, you should enter either an int or float number.
Second run:
Enter a number: 0
Result is infinity because you have entered zero value.
Third run:
Enter a number: 5.5
Result: 3.6363636363636362
Adding an Else Block (Try-Except-Else Block)
We can also add a single else clause or block after all the except block in a try-except block. However, it is an optional part that will execute only if no exception will occur within the try block. The general syntax to define try-except-else block is as follows:
try:
statement(s)
except(ExceptionType1):
statement(s)
except(ExceptionType2):
statement(s)
. . . .
else:
statement(s)
Example 6:
try:
age = int(input("Enter your age in years: "))
except(ValueError):
print("This is not a valid input.")
else:
print("Your age = ", age)
Output:
First run:
Enter your age in years: 30
Your age = 30
Second run:
Enter your age in years: good
This is not a valid input.
As you can see in the above example, else block is executed only when there is no exception raised within the try block. If we enter other than a numeric value, except block code will execute.
Example 7:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except ValueError:
print("Please enter valid integers")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("The result of division is: ", result)
Output:
First run:
Enter a number: 20
Enter another number: 0
Cannot divide by zero
Second run:
Enter a number: 100
Enter another number: 2
The result of division is: 50.0
In this example, we have defined a try block in which we attempt to get user input for two numbers and perform division. If we enter a non-integer number, a ValueError exception occurs and prints a user-defined message on the console.
If we enter zero as the second number, it generates a ZeroDivisionError exception, and prints a user-defined message. In case, no exceptions are raised, the else block executes and prints the result of the division.
In this tutorial, we have explained handling multiple exceptions in Python with the help of various example programs that is very important for practice. Hope that you will have understood the basic concept of try-except-else block and practiced all programs based on them. In the next tutorial, we will learn finally block in Python.
Thanks for reading!!!





