Exception Groups with except* in Python

Level 5215 keystrokes

Raises an ExceptionGroup holding two errors and handles each type separately with except*.

Python code

1errors = [ValueError("bad"), TypeError("oops")]
2try:
# ExceptionGroup bundles several errors into one exception
3 raise ExceptionGroup("errs", errors)
# except* extracts only the ValueError members of the group
4except* ValueError as eg:
5 print("value:", eg.exceptions)
# A second except* handles the TypeError member, so both blocks run
6except* TypeError as eg:
7 print("type:", eg.exceptions)
8print("done")

Output

value: (ValueError('bad'),)
type: (TypeError('oops'),)
done
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 12
  • (× 6
  • )× 6
  • :× 5
  • ,× 4
  • .× 2
  • *× 2
  • [× 1
  • ]× 1
  • =× 1

More Python examples at level 5

← Python typing practice