Python is a popular programming language that is widely used by developers for various purposes, including web development, data analysis, and machine learning. One of the key features of Python is its ability to handle exceptions gracefully.
Exceptions are errors that can occur during the execution of a program and can cause it to terminate abruptly. In this article, we will explore how to handle multiple exceptions in Python and provide an example function to add items to a list.
Handling Multiple Exceptions using Multiple Except Blocks
In Python, you can use multiple except blocks to catch multiple exceptions. Each except block handles a specific exception, and you can have as many except blocks as needed.
Here’s an example:
try:
# some code here
except ValueError:
# handle ValueError here
except TypeError:
# handle TypeError here
In the above code, the try block contains the code that may raise exceptions. The except blocks are executed if an exception of the corresponding type occurs.
In this case, we have two except blocks to handle ValueError and TypeError.
Using a Single Except Block to Handle Multiple Exceptions
Sometimes, you may want to handle multiple exceptions using a single except block. This is possible in Python using parentheses to group the exceptions.
Here’s an example:
try:
# some code here
except (ValueError, TypeError):
# handle ValueError and TypeError here
In the above code, we have combined the ValueError and TypeError exceptions into a tuple and passed it to the except block.
Example Function for Handling Multiple Exceptions
Now let’s take a look at an example function that adds items to a list.
def add_list(lst, item):
if isinstance(item, int):
lst.append(item)
else:
raise ValueError("Only integers allowed")
In the above code, the add_list function takes a list and an item as inputs.
The function checks if the item is an integer using the isinstance function. If the item is an integer, it is added to the list using the append method.
If the item is not an integer, a ValueError is raised with an error message “Only integers allowed”.
Handling Exceptions in the Function
To handle exceptions in the add_list function, we can use a try-except block. Here’s an example:
try:
add_list(["a", "b", "c"], "d")
except ValueError as e:
print(e)
In the above code, we have called the add_list function with a list of strings and a string item.
Since strings are not integers, the function will raise a ValueError. We have used a try-except block to catch the exception and print the error message.
Conclusion
In this article, we have seen how to handle multiple exceptions in Python using both multiple except blocks and a single except block. We have also provided an example function to add items to a list and shown how to handle exceptions in the function using a try-except block.
By mastering exception handling in Python, developers can write more robust and error-resistant code, improving the stability and reliability of their applications. In the previous sections, we discussed how multiple exceptions can be handled in Python using various methods.
In this section, we will see how to run a function that handles multiple exceptions and the corresponding output of the code. Additionally, we will provide a brief summary of the two ways of handling multiple exceptions in Python.
Running the Function on Input Lists
Let us assume we have two input lists, input_list_1
and input_list_2
. We will pass these lists to the function we defined in the earlier section.
input_list_1 = [1, 2, 'a', 4, 'b']
input_list_2 = [1, '2', 3, '4', 5]
add_items_to_list(input_list_1)
add_items_to_list(input_list_2)
In the above code, we have defined two lists, input_list_1
and input_list_2
. We are calling the add_items_to_list()
function and passing the two input lists as arguments.
Printing the Output of Function with Exceptions
When the function is run with input_list_1
, a ValueError
is raised since the list contains both integers and strings. Similarly, when the function is run with input_list_2
, a TypeError
is raised since one of the items is a string.
Let us print the output of the function with exceptions.
try:
add_items_to_list(input_list_1)
except ValueError as e:
print(e)
try:
add_items_to_list(input_list_2)
except TypeError as e:
print(e)
In the above code, we have used a try-except
block to handle the exceptions raised by the function when run with input_list_1
and input_list_2
.
We have also printed the error messages that are raised. The output of the code will be as follows:
Cannot add non-integers to the list
'int' object is not iterable
The first error message “Cannot add non-integers to the list” is due to the fact that input_list_1
contains strings. The second error message “‘int’ object is not iterable” is due to the fact that input_list_2
contains the string ‘2’ instead of an integer.
Two Ways of Handling Multiple Exceptions
In this article, we have seen two ways of handling multiple exceptions in Python: using multiple except blocks and using a single except block.
When using multiple except blocks, each except block handles a specific exception.
This is useful when we need to take different actions depending on the type of exception that is raised.
On the other hand, when using a single except block, we can group multiple exceptions together and handle them in the same block.
This is useful when we want to take the same action for multiple types of exceptions. Both approaches have their own advantages and disadvantages.
The choice of which method to use depends on the specific requirements of the code and the developer’s personal preference.
Conclusion
In this article, we have explored how to handle multiple exceptions in Python using multiple except blocks and a single except block. We have also provided an example function that adds items to a list and shown how to handle exceptions in the function using a try-except block.
Finally, we have seen how to run the function on input lists and print the output of the function with exceptions. By mastering exception handling in Python, developers can write more robust and error-resistant code, improving the stability and reliability of their applications.
In conclusion, this article has highlighted the importance of handling multiple exceptions in Python and provided two main techniques for doing so. The article has shown how to use multiple except blocks to handle specific exceptions and a single except block to group multiple exceptions together.
An example function has been used to demonstrate how to handle exceptions in practice. The article has emphasized the significance of mastering exception handling in Python for building more reliable and robust applications.
Developers who can write error-resistant code enhance the quality of their work and can deliver more reliable software products. With the techniques discussed in this article, programmers can ensure their code performs well even with unexpected and exceptional conditions.