Search code examples
pythonexceptiontry-exceptfinally

How to avoid duplicates when python multiple except executes the same method?


I have the code block like below:

try:
   method()
except ErrorType1:
   todo()
   return
except ErrorType2 as e:
   todo()
   raise e

Basically for the two error types, I need to execute todo() first, then either return or raise e. Is it possible to just write todo() once? I was thinking using finally but don't think that actually works.


Solution

  • You could catch both exceptions in one except clause, execute todo and then decide to do based on the exception type:

    try:
       method()
    except (ErrorType1, ErrorType2) as e:
       todo()
       if isinstance(e, ErrorType1):
           return
       raise
    

    Note - as pointed out by @ShadowRanger in the comments to the question - you should just use raise to re-raise the existing exception, using raise e will raise a second copy of it, resulting in the traceback including the line with raise e on it as well as the line where the original error occurred.