Saturday, December 28, 2024
Google search engine
HomeLanguagesException Groups in Python

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 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:

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments