Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python Exception Groups and except* code

Practice creating exception groups and handling their matching subgroups with except*.

Advanced ~7 min read

Challenge 1

Raise one ExceptionGroup containing ValueError("bad age") and TypeError("bad name"), then print how many exceptions it contains.

python Your answer
failures = [ValueError("bad age"), TypeError("bad name")]
try:
    
except ExceptionGroup as group:
    print(len(group.exceptions))

Press Ctrl⌘Enter to check your answer

Challenge 2

Handle the ValueError part of the group and print its messages, while leaving the TypeError part unprinted.

python Your answer
try:
    raise ExceptionGroup("input", [ValueError("age"), TypeError("name")])

except* TypeError:
    pass

Press Ctrl⌘Enter to check your answer

Challenge 3

Add an except* handler for TypeError that prints the matched exception type names.

python Your answer
try:
    raise ExceptionGroup("mixed", [ValueError("a"), TypeError("b")])
except* ValueError:
    pass

Press Ctrl⌘Enter to check your answer

Challenge 4

Catch the unmatched ExceptionGroup with an outer except and print the remaining exception type names.

python Your answer
try:
    try:
        raise ExceptionGroup("mixed", [ValueError("a"), KeyError("b")])
    except* ValueError:
        pass

Press Ctrl⌘Enter to check your answer