CodeBlanks Logo Icon CodeBlanks

Summary - Advanced exceptions

Combine multiple except, chaining and traceback to write an error reporter.

Summary - Advanced exceptions

In this group you learned advanced exception-handling techniques. Multiple except blocks catch different types; the except (A, B): tuple form matches several types in one block. With as e you bind the error object to a variable.

raise X from e builds a chain; the __cause__ attribute gives access to the original error. traceback.format_exc() returns the full stack trace as a string. These tools make error handling robust in production applications.

Mini task: catch and chain

In the summary task you'll catch an error and convert it to another. The inner try raises ValueError; the except ValueError as e: block does raise RuntimeError("conversion") from e. The outer except RuntimeError as e: prints the type and cause.

This task shows chaining, as e and type-info extraction together. The output is two lines: first the new error type, then the cause type.

Practice Chain and print types

Write nested try. In the inner block do value = int("abc"); in except ValueError as e: write raise RuntimeError("conversion") from e. In the outer except RuntimeError as e: write print(type(e).__name__) and print(type(e.__cause__).__name__).

Starter code

main.py
# Write nested try
# Inner: convert ValueError to RuntimeError
# Outer: print type and cause type

Sample solution

main.py
# Write nested try
try:
    # Inner: convert ValueError to RuntimeError
    try:
        value = int("abc")
    except ValueError as e:
        raise RuntimeError("conversion") from e
# Outer: print type and cause type
except RuntimeError as e:
    print(type(e).__name__)
    print(type(e.__cause__).__name__)

Expected output

RuntimeError
ValueError

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which word is used to access the error object?

  • as Correct answer
  • is
  • to
  • be

Explanation: as e binds the error object to the variable e.

2 Complete raise from e

Question
raise RuntimeError("Error") ____ e
Answer
raise RuntimeError("Error") from e

Explanation: The from e clause chains the original error.

3 Match the advanced exception concepts

Term Meaning
except (A, B) Multi-type tuple
as e Binds object to e
from e Chaining keyword
format_exc Returns trace as string

All lessons in Intermediate