I'm starting to notice this pattern throughout some of my code:
try: some_func() except FirstException as err: # known possible err # log err notify_user(err) except SecondException as err: # known possible err # log err notify_user(err) except Exception as err: # unexpected err to prevent crash # log err notify_user(err) finally: # close logs
It should be noted that
some_func does not explicitly raise these exceptions, but calls other methods that may propagate them back up the call stack. While its clean and clear that each exception caught will get its own logging (which presumably has a unique message), they all call the same
notify_user. Therefore, this structure is not DRY, so I thought:
try: some_func() except Exception as err: # catch all (presumably) exceptions if isinstance(err, FirstException): # log err elif isinstance(err, SecondException): # log err else: # log err notify_user(err) finally: # close logs
While also clear that logging is specific to the desired error caught, its now DRY.
But doesn't this defeat the point of knowing know exception types by trying to catch all exceptions and using conditionals to identify which is caught? Broad exception catching seems "okay" in concept, but I'm concerned it could lead to some unforeseen consequences later.