Back to results for “Exception Handling”
Python › Exception Handling

How does context manager __exit__ interact with exception handling, and how can it SUPPRESS an exception by returning True?

Advanced

Answer

__exit__(self, exc_type, exc_value, traceback) receives details of any exception raised inside the 'with' block; if it returns a TRUTHY value, the exception is SUPPRESSED entirely (treated as handled, execution continues after the 'with' block) — returning None/False (the default) lets the exception propagate normally.
class SuppressErrors:
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, tb):
        if exc_type is ValueError:
            print(f"Suppressed: {exc_value}")
            return True  # suppresses the ValueError
        return False  # lets other exception types propagate normally

with SuppressErrors():
    raise ValueError("this gets suppressed")
print("Execution continues here")
Real-world example Building a custom context manager (similar to contextlib.suppress) that intentionally swallows specific, expected exception types.

Common follow-ups: How does the standard library's contextlib.suppress() context manager provide this exact same capability more concisely?