Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Different Exceptions 
3.
Handling multiple exceptions 
3.1.
Example 1
3.1.1.
Code:
3.1.2.
Explanation:
3.2.
Example 2
3.2.1.
Code:
3.2.2.
Explanation:
3.3.
Example 3
3.3.1.
Code:
3.3.2.
Explanation:
3.4.
Code:
3.4.1.
Explanation:
3.5.
Example 4
3.5.1.
Code:
3.5.2.
Output: 
3.5.3.
Explanation:
4.
FAQs
4.1.
Why do we say that exceptions occur at runtime only? 
4.2.
What is the difference between exception and syntax errors?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Multiple exception handling in python

Author Ayushi Poddar
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Whenever there is an unusual condition encountered in a program that results in the interruption in the flow of the program, it is termed an exception. As soon as an exception occurs, the program stops the execution, and hence the further code is not executed. That is why an exception happens due to some run-time error that the Python script cannot handle. In Python, we have different ways to handle these exceptions so that the code can be executed without any halt caused due to the exception encountered.

Also see,  Convert String to List Python

Different Exceptions 

Python helps with several built-in exceptions, and the following is a list of some common exceptions that a standard Python program can throw.

  • EOFError
    This error occurs when the end of the file is reached, but still, some operations are left to perform.
  • IOError
    This error occurs when the Input Output operation fails.
  • ZeroDivisionError
    This error occurs when a number is divided by zero.
  • NameError
    This error occurs when the python script is not able to find a name.
  • IndentationError
    This error occurs when the Input Output operation fails.

 

You can also read about the Multilevel Inheritance in Python, Fibonacci Series in Python.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Handling multiple exceptions 

Example 1

One can handle different exceptions by using a single block of code, which can be grouped in a tuple, as shown in the example below.

Code:

try:
client_obj.get_url(url)
except (URLError, ValueError, SocketTimeout):
    client_obj.remove_url(url)

Explanation:

The remove_url() method will have to be called if any of the listed exceptions occur.

Example 2

On the other hand, if any exceptions have to be handled separately, then the following code could help us.

Code:

try:
    client_obj.get_url(url)
except (URLError, ValueError):
    client_obj.remove_url(url)
except SocketTimeout:
    client_obj.handle_url_timeout(url)

Explanation:

Here we separated the two exceptions, and thus, they can be handled separately now.

Example 3

Now instead of putting exceptions grouped into an inheritance hierarchy, all the exceptions can be caught simply by specifying a base class, like in the code given below.

Code:

try:
    f = open(filename)
except (FileNotFoundError, PermissionError):

Explanation:

Here in the above code, the except statement follows a hierarchy, and we can omit this by using the given code below.

Code:

try:
    f = open(filename)
except OSError:

Explanation:

The OSError mentioned above is a base class that is common to both the FileNotFoundError and also the PermissionError exceptions. Hence, it can be used to replace the hierarchy easily.

Example 4

It is unnecessary to handle multiple exceptions, and hence one can get a handle on the thrown exception using them as a keyword as used in the given code.

Code:

try:
    f = open(filename)
  
except OSError as e:
    if e.errno == errno.ENOENT:
        logger.error('File not found')
    elif e.errno == errno.EACCES:
        logger.error('Permission denied')
    else:
        logger.error('Unexpected error: % d', e.errno)

Output: 

File not found

Explanation:

The ‘e’ variable used above basically holds an instance of the raised OSError. This can prove useful if the exception has to be invested even further, maybe to process it based on the value of the additional status code.The clauses of the except are checked in the order list, and the first match is executed.

You can try it on online python compiler.

Also Read,  leap year program in python

FAQs

Why do we say that exceptions occur at runtime only? 

Exceptions are encountered while the program is running and are caused due to run time errors and not the errors due to syntax mistakes or compile time errors, and that’s why they occur only at runtime.


What is the difference between exception and syntax errors?

Syntax errors are identified by the compiler before the program is even executed, while exceptions are identified only when the program which is free of any syntax errors is being executed, and there some error is encountered.

Conclusion

This article extensively discussed the handling of exceptions in python. Exception handling is essential such that whenever any wrong user input or any other related issue is raised, the program can handle it well. We hope that this blog has helped you enhance your knowledge regarding Abstract  Lists and if you would like to learn more, check out our articles on Coding Ninjas.

Do upvote our blog to help other ninjas grow. Happy Coding!

 

Previous article
The OSError in Python
Next article
Handling a thread's exception in the caller thread in Python
Live masterclass