Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Grouping Exceptions

00:00 In the previous lesson, I talked about the assert keyword. In this lesson, I’ll introduce you to exception groups. Python 3.11 added a new feature to exceptions, a way of grouping them together.

00:13 This gets done using the ExceptionGroup class, which is a kind of exception container and an exception. In addition to the new class, some new syntax got added as well.

00:24 By putting a star on the end of the except keyword, you can specify that the except handling block is supposed to work with an exception that’s inside of an ExceptionGroup as well.

00:35 Groups don’t get used all that frequently, but they can be handy when you’re in a situation where different kinds of exceptions can happen at the same time.

00:45 This can occur if you’re writing asynchronous code where each thread could fail in a different way. Let’s go play with an ExceptionGroup. Let’s start with a simple try/except block that by now you’re very familiar with.

00:59 The block raises a ValueError and the exception handler handles it, calling print(). So far so good. Now let’s try the new syntax.

01:12 Same try block, but now instead I’m using except* As there aren’t any exception groups here, the same thing happens as before. Adding the star doesn’t break the regular exception handling mechanism.

01:35 This time I’ve got two exception handlers, both using the star syntax. As the try block only raises a ValueError, the extra handler in this case isn’t going to get called.

01:46 Alright, now what you came for. A group.

01:55 Instead of raising a regular exception, I’m raising an ExceptionGroup this time. The ExceptionGroup class starts out with a message, then takes a list of exceptions that get grouped together.

02:14 My ExceptionGroup is going to contain a ValueError and a KeyError. Like before I’m using the except* syntax.

02:36 Since the ExceptionGroup has both a ValueError and a KeyError inside it, and the exception handlers are using the star syntax, both the ValueError and KeyError handlers get invoked.

02:49 Let’s take a look at what happens if you don’t handle the group.

03:10 Like with a regular exception, you get a stack trace, but this one has some pretty printed info on the exceptions contained within the group. Instead of handling the exceptions inside the group, you can also handle the group itself.

03:37 To handle the group, you simply treat the ExceptionGroup object as if it were a plain old exception. And there you go. The group got handled.

03:48 That’s pretty much it. In the last lesson, I’ll summarize the course.

Become a Member to join the conversation.