The Wayback Machine - https://web.archive.org/web/20240930235858/https://www.geeksforgeeks.org/exception-groups-in-python/
Open In App

Exception Groups in Python

Last Updated : 08 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 we can group together different Exceptions which we can later fetch one by one whenever necessary, the order in which the Exceptions are stored in the Exception Group doesn’t matter while calling them.

NOTE: If the user doesn’t have Python 3.11 installed on their device then this will not work.

Syntax of ExceptionGroup

Syntax: ExceptionGroup(“<User_Message/Description>”,[<SubException1(“exception message”)>,

                  <SubException2(“exception message”)>,…. <SubExceptionN(“exception message”)>])

Parameter: ExceptionGroup takes two parameters. 

  • First_Parameter – A message/description of what kind of Exceptions it will be storing or anything user wants to write there as a message of the ExceptionGroup.
  • Second_Parameter – Any amount of sub-exceptions user want to store with their respective messages.

Example

As you can see, even though we have created a function exceptionGroup() we are not returning any value, rather than that we are raising the variable in which we are storing the ExceptionGroup, because as we know in case of exception handling we raise an Exception. Now let’s create an ExceptionGroup and see how it works.

Python3




def exceptionGroup():
    exec_gr = ExceptionGroup('ExceptionGroup Message!',
                [FileNotFoundError("This File is not found"),
                ValueError("Invalid Value Provided"),
                ZeroDivisionError("Trying to divide by 0")])
    raise exec_gr


Now, what happens if we call this Function?

Users will get a structured new kind of error message which clearly states the number of Sub Exceptions we have in the Exception Group with their respective messages.

Python3




exceptionGroup()


Output:

 

Now enclose them in a Python try-except block

In the snippet, we are using the traditional method of try-except block and calling the entire Exception group in except block and printing all the Sub Exception messages we have inside it. It will yield the following output.

Python3




try:
    exceptionGroup()
except ExceptionGroup as eg:
    print(eg.exceptions)


Output 

The above snippet will return the following output, it is just printing all the Sub Exceptions and their messages in a tuple form.

 

Handling a single Exception from the ExceptionGroup

There is another great way to handle Sub Exceptions one by one without handling them all together like the above traditional method. For that, there is a new syntax – except*, which is used specifically with ExceptionGroup.

except* <ExceptionName> as <any_alias>:
    print(<any_alias>.exception)

Example

Python3




try:
    exceptionGroup()
except* FileNotFoundError as fnf:
    print(fnf.exceptions)
except* ValueError as ve:
    print(ve.exceptions)
except* ZeroDivisionError as zde:
    print(zde.exceptions)


Output:

 

As we can see, all the Exceptions and their respective error messages are displayed. Now if we want to only print the messages then we have to write code as below:

Python3




# only one except part is given here, the try block would be same.
# the way of printing the rest of the except blocks will be same also
  
except* FileNotFoundError as fnf:
    for err in fnf.exceptions:
        print(err)


Output:

 

In case we only handle a single exception but there is more than one unhandled exception we will get output like this below:

 

As we can see that Python will give us the name of the Unhandled exceptions and their messages in a structured manner.

Nested Exception Group

We can have an ExceptionGroup inside of an ExceptionGroup i.e Nested Exception group. We will get this amazing structured output which clearly tells us about our nested Exception Group alongside our real Exception Group.

Python3




# defining the exception group function with a Nested exception group
def exceptionGroup():
    exec_gr = ExceptionGroup('ExceptionGroup Message!',
                             [FileNotFoundError("This File is not found"),
                              ValueError("Invalid Value Provided"),
                              ZeroDivisionError("Trying to divide by 0"),
                              ExceptionGroup("This is a Nested ExceptionGroup",
                                             [IndentationError("Please check your Indentation"),
                                              SyntaxError(
                                                 "there is a error in the syntax"),
                                                 ImportError("Module Not Found")])])
    raise exec_gr
  
  
# calling the function
exceptionGroup()


Output:

 



Similar Reads

Python | Raising an Exception to Another Exception
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. Code #1 : def example(): try: in
2 min read
Multiple Exception Handling in Python
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 th
3 min read
Python | Reraise the Last Exception and Issue Warning
Problem - Reraising the exception, that has been caught in the except block. Code #1: Using raise statement all by itself. def example(): try: int('N/A') except ValueError: print("Didn't work") raise example() Output : Didn't work Traceback (most recent call last): File "", line 1, in File "", line 3, in example ValueError: invalid litera
2 min read
Create an Exception Logging Decorator in Python
Prerequisites: Decorators in Python, Logging in Python Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice.
2 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional
2 min read
Test if a function throws an exception in Python
The unittest unit testing framework is used to validate that the code performs as designed. To achieve this, unittest supports some important methods in an object-oriented way: test fixturetest casetest suitetest runner A deeper insight for the above terms can be gained from https://www.geeksforgeeks.org/unit-testing-python-unittest/ assertRaises()
4 min read
How to print exception stack trace in Python?
Prerequisite: Python Traceback To print stack trace for an exception the suspicious code will be kept in the try block and except block will be employed to handle the exception generated. Here we will be printing the stack trace to handle the exception generated. The printing stack trace for an exception helps in understanding the error and what we
3 min read
Handling TypeError Exception in Python
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeError being raised are: 1. Unsupported Operation Betwe
3 min read
How to print the Python Exception/Error Hierarchy?
Before Printing the Error Hierarchy let's understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let's try to print the
3 min read
EnvironmentError Exception in Python
EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions. exception IOError - It is raised when an I/O operation (when a method of a file object ) fails. e.g "File not found" or "Disk Full".exception OSError - It is raised when
1 min read
Handling OSError exception in Python
Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as "file not found" or "disk full". Below is an example of OSError: Python Code # Importing
2 min read
How to handle a Python Exception in a List Comprehension?
An exception is something that interrupts the flow of the program. These exceptions stop the process running and sends out an error message. Exceptions can be simply viewed as an object that represents an error. There are predefined exceptions and user-defined exceptions in Python. In this article, we will discuss how to handle Python exception in
5 min read
Handling a thread's exception in the caller thread in Python
Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception handling, try-except blocks are used that catch the ex
3 min read
Handling EOFError Exception in Python
EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box. We can overcome this issue by using try and except
1 min read
How to Ignore an Exception and Proceed in Python
There are a lot of times when in order to prototype fast, we need to ignore a few exceptions to get to the final result and then fix them later. In this article, we will see how we can ignore an exception in Python and proceed. Demonstrate Exception in Python Before seeing the method to solve it, let's write a program to raise an error. C/C++ Code
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, they are not identified at compile time just like sy
3 min read
Exception Handling Of Python Requests Module
Python request module is a simple and elegant Python HTTP library. It provides methods for accessing Web resources via HTTP. In the following article, we will use the HTTP GET method in the Request module. This method requests data from the server and the Exception handling comes in handy when the response is not successful. Here, we will go throug
4 min read
Python Print Exception
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. In this article, we are going to focus on 'How can we print an exception in Py
5 min read
How to catch a NumPy warning like an exception in Python
An N-dimensional array that is used in linear algebra is called NumPy. Whenever the user tries to perform some action that is impossible or tries to capture an item that doesn't exist, NumPy usually throws an error, like it's an exception. Similarly, in a Numpy array, when the user tries to perform some action that is impossible or tries to capture
3 min read
How to log a Python exception?
To log an exception in Python we can use a logging module and through that, we can log the error. The logging module provides a set of functions for simple logging and the following purposes DEBUGINFOWARNINGERRORCRITICALLog a Python Exception Examples Example 1:Logging an exception in Python with an error can be done in the logging.exception() meth
2 min read
Fix SystemError: Initialization of _internal Failed without Raising an Exception in Python?
In Python, a "SystemError: Initialization of _internal Failed without Raising an Exception" generally happens during the initialization of Python modules or libraries, leading to program crashes or unexpected behavior. In this article, we will learn how to resolve SystemError: Initialization of _internal Failed without Raising an Exception. Underst
4 min read
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 functions: In the below example code, the print statement
2 min read
Python Exception Handling
We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4).  In this article, we will discuss how to handle exceptions in Python using try, except, and finally statements with the help of proper examples.  Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a program due to which
9 min read
Exception Handing in Django
In this article, we will explore exception handling in Django, examining its significance and learning how to effectively manage exceptions. Through a practical example, we will illustrate the concept and subsequently delve into the solutions for handling exceptions. Exception Handing in DjangoHere, we are explaining exceptions handing in Django in
6 min read
Python Slicing | Reverse an array in groups of given size
Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] k = 3 Output: [3, 2, 1, 6, 5, 4, 9, 8, 7] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 Output: [5, 4, 3, 2, 1, 8, 7, 6] Input: arr = [1, 2, 3, 4, 5, 6] k = 1 Output: [1, 2, 3, 4, 5, 6] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k =
5 min read
Python | User groups with Custom permissions in Django
Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the different packages available on tour booking servi
4 min read
How to Iterate over Dataframe Groups in Python-Pandas?
In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: C/C++ Code # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframe df = pd.DataFrame(dict) # show
2 min read
re.MatchObject.groups() function in Python - Regex
This method returns a tuple of all matched subgroups. Syntax: re.MatchObject.groups() Return: A tuple of all matched subgroups AttributeError: If a matching pattern is not found then it raise AttributeError. Consider the below example: Example 1: C/C++ Code import re """We create a re.MatchObject and store it in match_object variable
2 min read
Set the amount of vertical space between legend groups using Plotly-Python
In this article, we will learn how to set the amount of vertical space between legend groups. A legend is an area describing the elements of the graph. In the plotly legend is used to Place a legend on the axes. Example 1: In this Bar chart, We are setting the amount of vertical space (in px) between legend groups with the help of a method called f
1 min read
Python Regex: Replace Captured Groups
Regular Expressions, often abbreviated as Regex, are sequences of characters that form search patterns. They are powerful tools used in programming and text processing to search, match, and manipulate strings. Think of them as advanced search filters that allow us to find specific patterns within a text, such as email addresses, dates, phone number
5 min read
Practice Tags :