pythonexceptionerror-handlingcontextmanager

Exception silently ignored inside context manager decorated method


The following code appears not to raise. Is that a bug or have I not correctly understood the error handling in context managers?

from contextlib import contextmanager

class Dataset:
    _getToRaise = False
    
    def __getitem__(self, index):
        if self._getToRaise:
            print("It is supposed to raise here")
            raise ValueError
        return 0
    
    @contextmanager
    def getToRaise(self):
        try:
            self._getToRaise = True
            print('Entering context manager')
            yield
        finally:
            print('Exiting context manager')
            self._getToRaise = False
            return
    
d = Dataset()
with d.getToRaise():
    d[0]

Running the code in Python 3.8.17 returns:

Entering context manager
It is supposed to raise here
Exiting context manager

and no exception is raised...


Solution

  • The problem is the return in the finally-block:

        @contextmanager
        def getToRaise(self):
            try:
                self._getToRaise = True
                print('Entering context manager')
                yield
            finally:
                print('Exiting context manager')
                self._getToRaise = False
                # return    <---- Comment out or remove