Suppose I have 2 exceptions:
class FooError (Exception): def __init__(self, *args, **kwargs): default_message = 'A foo error has occurred!' if not (args or kwargs): args = (default_message,) super().__init__(*args, **kwargs) class BarError (Exception): def __init__(self, *args, **kwargs): default_message = 'A bar error has occurred!' if not (args or kwargs): args = (default_message,) super().__init__(*args, **kwargs) And, I have a function which throws FooError:
def foobar (x): if x < 0: raise FooError() Generally, you would handle FooError with a try/except block:
try: foobar(-1) except FooError: print('Uh oh, foo error!') sys.exit() However, I would like to throw a BarError which I can handle later. Something like this:
except BarError: print('Uh oh, bar error!') sys.exit() When executing this, though, I just get the traceback of both errors:
Traceback (most recent call last): File "C:\Users\Maze\Desktop\test2.py", line 17, in <module> foobar(-1) File "C:\Users\Maze\Desktop\test2.py", line 15, in foobar raise FooError() __main__.FooError: A foo error has occurred! During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Maze\Desktop\test2.py", line 19, in <module> raise BarError() __main__.BarError: A bar error has occurred! How do I throw BarError inside of the handler for FooError, and then handle BarError in a different except block?