Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Handling NameError Exception in Python
Next article icon

Multiple Exception Handling in Python

Last Updated : 12 Jun, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages.

If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in the code given below :

Code #1 :




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

The remove_url() method will be called if any of the listed exceptions occurs. If, on the other hand, if one of the exceptions has to be handled differently, then put it into its own except clause as shown in the code given below :

Code #2 :




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

Many exceptions are grouped into an inheritance hierarchy. For such exceptions, all of the exceptions can be caught by simply specifying a base class. For example, instead of writing code as shown in the code given below –

Code #3 :




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

Except statement can be re-written as in the code given below. This works because OSError is a base class that’s common to both the FileNotFoundError and PermissionError exceptions.

Code #4 :




try:
    f = open(filename)
except OSError:
    ...
 
 

Although it’s not specific to handle multiple exceptions per se, it is worth noting that one can get a handle to the thrown exception using them as a keyword as shown in the code given below.

Code #5 :




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)
 
 

The e variable holds an instance of the raised OSError. This is useful if the exception has to be invested further, such as processing it based on the value of the additional status code. The except clauses are checked in the order listed and the first match executes.

Code #6 : Create situations where multiple except clauses might match




f = open('missing')
 
 

Output :

  Traceback (most recent call last):  File "", line 1, in   FileNotFoundError: [Errno 2] No such file or directory: 'miss  




try:
    f = open('missing')
    except OSError:
        print('It failed')
    except FileNotFoundError:
        print('File not found')
 
 

Output :

  Failed  

Here the except FileNotFoundError clause doesn’t execute because the OSError is more general, matches the FileNotFoundError exception, and was listed first.



Next Article
Handling NameError Exception in Python

M

manikachandna97
Improve
Article Tags :
  • Python
  • Python-exceptions
Practice Tags :
  • python

Similar Reads

  • Handling NameError Exception in Python
    Prerequisites: Python Exception Handling There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are : 1. Misspelled built-in functio
    2 min read
  • Python Exception Handling
    Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example: Hand
    7 min read
  • How to Catch Multiple Exceptions in One Line in Python?
    There might be cases when we need to have exceptions in a single line. In this article, we will learn about how we can have multiple exceptions in a single line. We use this method to make code more readable and less complex. Also, it will help us follow the DRY (Don't repeat code) code method. Gene
    2 min read
  • Importing Multiple Files in Python
    Here, we have a task to import multiple files from a folder in Python and print the result. In this article, we will see how to import multiple files from a folder in Python using different methods. Import Multiple Files From a Folder in PythonBelow, are the methods of importing multiple files from
    2 min read
  • How to Call Multiple Functions in Python
    In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, we’ll explore various ways we can call multiple functions in Python. The most straightforward way to call multiple functions is by executing them one after
    3 min read
  • How to handle KeyError Exception in Python
    In this article, we will learn how to handle KeyError exceptions in Python programming language. What are Exceptions?It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.Exceptions are runtime errors because, th
    3 min read
  • Exception Groups in Python
    In this article, we will see how we can use the latest feature of Python 3.11, Exception Groups. To use ExceptionGroup you must be familiar with Exception Handling in Python. As the name itself suggests, it is a collection/group of different kinds of Exception. Without creating Multiple Exceptions w
    4 min read
  • File Handling in Python
    File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
    7 min read
  • Chain Multiple Decorators in Python
    In this article, we will try to understand the basic concept behind how to make function decorators and chain them together we will also try to see Python decorator examples.  What is Decorator In Python?A decorator is a function that can take a function as an argument and extend its functionality a
    2 min read
  • Check multiple conditions in if statement - Python
    If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true. Syntax: if (condition): code1else: code2[on_true] if [expression] else [on_false]Note: For more information, refer to Decision Making in Python (if , if..else, Nested if, if-eli
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences