Shalva
Shalva

Reputation: 55

How to handle exceptions in function-based context managers

In class based context managers you can handle and silence the expected exceptions in the exit method, and by returning true you can continue execution of the program.

    def __exit__(self, exc_type, exc_value, exc_tb):
    print("Leaving the context...")
    if isinstance(exc_value, IndexError):
        # Handle IndexError here...
        print(f"An exception occurred in your with block: {exc_type}")
        print(f"Exception message: {exc_value}")
        return True

I was wondering, is there a way of doing the same in function-based context managers? If yes, is that a good practice?

@contextmanager
def writable_file(file_path):
    file = open(file_path, mode="w")
    try:
        yield file
    finally:
        file.close()

Upvotes: 1

Views: 190

Answers (1)

sudden_appearance
sudden_appearance

Reputation: 2197

if you want to handle exceptions just handle them in try except block.

Do not forget to yield something when handling exceptions as it will raise

RuntimeException: generator didn't yield

Simple example of handling exception

from contextlib import contextmanager


@contextmanager
def divide(x, y):
    try:
        yield x / y

    except ZeroDivisionError as err:
        print("Zero division. Do not do that")
        yield None

    finally:
        ...
        # do some closing operations. DO NOT YIELD HERE!!!


with divide(5, 0) as result:
    print(result)

Upvotes: 2

Related Questions