Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Concrete Exceptions in Python
Next article icon

In this article, we will see how we can use the latest feature ofPython 3.11, Exception Groups. To useExceptionGroup you must be familiar withException Handling inPython. 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 functionexceptionGroup() we are not returning any value, rather than that we areraising the variable in which we are storing the ExceptionGroup, because as we know in case of exception handling weraise an Exception. Now let's create an ExceptionGroup and see how it works.

Python3
defexceptionGroup():exec_gr=ExceptionGroup('ExceptionGroup Message!',[FileNotFoundError("This File is not found"),ValueError("Invalid Value Provided"),ZeroDivisionError("Trying to divide by 0")])raiseexec_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 oftry-except block and calling the entire Exception group inexcept block and printing all the Sub Exception messages we have inside it. It will yield the following output.

Python3
try:exceptionGroup()exceptExceptionGroupaseg: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*FileNotFoundErrorasfnf:print(fnf.exceptions)except*ValueErrorasve:print(ve.exceptions)except*ZeroDivisionErroraszde: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 alsoexcept*FileNotFoundErrorasfnf:forerrinfnf.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 groupdefexceptionGroup():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")])])raiseexec_gr# calling the functionexceptionGroup()

Output:

 

Similar Reads

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

[8]ページ先頭

©2009-2025 Movatter.jp