How to catch an exception while using a Python \'with\' statement?

In Python, the with statement is used when working with files or network connections. It ensures that resources are opened, used, and then closed properly, even if an error occurs during the process.

If you want to catch any exceptions that happen inside a with block, you can wrap it in a try-except statement. Alternatively, you can use a custom context manager that handles exceptions on its own.

Using try-except with the with Statement

To catch errors that occur inside a with block, place it within a try-except structure. This helps you handle any exceptions that occur when working with resources ?

Example

In this example, we open a file using a with statement and try to read an integer from the file. If the file contains invalid data, a ValueError may be raised, which we catch and handle ?

try:
    # Create and write a number to the file
    with open("numbers.txt", "w") as file:
        file.write("ab3")  # Invalid integer value to test exception

    # Now open and read the file
    with open("numbers.txt", "r") as file:
        data = file.read()
        number = int(data)  # This may raise ValueError if data is not a valid integer
    print("Number read:", number)
except ValueError:
    print("Caught ValueError: invalid integer in file")
except FileNotFoundError:
    print("Caught FileNotFoundError: file not found")

The output of the above code is ?

Caught ValueError: invalid integer in file

Custom Context Manager for Exception Handling

A context manager is a Python object that defines what happens when you enter and exit a with block using its __enter__() and __exit__() methods. You can use it to automatically handle exceptions and even suppress them if needed.

The __exit__() method receives three parameters: exception type, exception value, and traceback. If it returns True, the exception is suppressed ?

Example

Following is a simple custom context manager that catches exceptions internally and suppresses them ?

class SuppressErrors:
    def __enter__(self):
        print("Entering context")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            print(f"Caught exception inside context manager: {exc_val}")
            return True  # Suppress the exception

with SuppressErrors():
    x = 1 / 0  # Raises ZeroDivisionError but is suppressed
print("Program continues after with block")

The output of the above code is ?

Entering context
Caught exception inside context manager: division by zero
Program continues after with block

Using contextlib.suppress()

Python's contextlib module provides a convenient suppress() function to suppress specific exceptions within a with block ?

from contextlib import suppress

# Suppress specific exceptions
with suppress(ZeroDivisionError, ValueError):
    result = 1 / 0  # This would normally raise ZeroDivisionError
    print("This won't be printed")

print("Program continues normally")

The output of the above code is ?

Program continues normally

Comparison

Method Exception Handling Best For
try-except Catches and handles exceptions When you need custom error handling logic
Custom Context Manager Can suppress or handle exceptions Reusable exception handling patterns
contextlib.suppress() Suppresses specific exceptions Simple exception suppression

Conclusion

Use try-except around with statements for standard exception handling. For suppressing specific exceptions, contextlib.suppress() provides a clean solution. Custom context managers offer the most flexibility for complex exception handling scenarios.

Updated on: 2026-03-24T16:30:01+05:30

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements