How do you handle an exception thrown by an except clause in Python?
def safeLoopingCall(self, *args, **kwargs):
try:
self.loopingCall(*args, **kwargs)
except:
self.log.exception("exception in task")
If an exception happens in the logger, we're out. What are best practices to avoid that? Do you surround an except by another try-except block (sounds awful)? This function is supposed to never propagate any exception.
-
2Which logger do you use? The default 'logging' module swallows the exceptions which have occured during logging: docs.python.org/library/…aeter– aeter2010年12月07日 16:21:53 +00:00Commented Dec 7, 2010 at 16:21
-
1Indeed. You need to specify logging.raiseExceptions = 0 to swallow exceptions. That works for this case. Thanks!Tommy– Tommy2010年12月07日 17:58:58 +00:00Commented Dec 7, 2010 at 17:58
2 Answers 2
In general it is not good design to have a catch-all except block, as it can mask programming errors. IMHO this is why it looks a little awful.
If you really want to fail graciouslly no matter what, then yes, put a nested try inside the except clause - but log the full traceback, otherwise it can get really hard to debug.
Comments
FWIW, you can have a look at my CausedException class. Maybe it can help you in this case; you would have to catch both exceptions, wrap them into CausedException and then should raise a CausedException with those two as reasons. This way all involved stack traces will be available in the debug message.