0

I'm trying to catch two exceptions as follows:

class TestException:
    def __init__(self):
        self.x = [1, 2, 3]

def main():
    test_exception = TestException()
    try:
        test_exception.y[1] = 4.0
    except (IndexError, AttributeError) as e:
        raise e('Why does this not work?')

if __name__ == '__main__':
    main()

but I get the following error:

TypeError: 'AttributeError' object is not callable

Why does this occur? Because the following works fines:

raise AttributeError('This does work!')

Thanks for any help.

ajrlewis
  • 2,968
  • 3
  • 33
  • 67
  • 4
    `e` is the *instance*, not the class. Either use `type(e)` to get the class, or look at `raise from` (see e.g. https://stackoverflow.com/q/24752395/3001761). – jonrsharpe Jun 11 '19 at 10:44

1 Answers1

0

Following on from @jonrsharpe, the following works fine:

raise type(e)('This works now.')

or

raise Exception('This works now.') from e
ajrlewis
  • 2,968
  • 3
  • 33
  • 67