4

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.

asked Dec 7, 2010 at 16:09
2
  • 2
    Which logger do you use? The default 'logging' module swallows the exceptions which have occured during logging: docs.python.org/library/… Commented Dec 7, 2010 at 16:21
  • 1
    Indeed. You need to specify logging.raiseExceptions = 0 to swallow exceptions. That works for this case. Thanks! Commented Dec 7, 2010 at 17:58

2 Answers 2

5

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.

answered Dec 7, 2010 at 16:22
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Duncan Jones
69.8k32 gold badges204 silver badges262 bronze badges
answered Sep 5, 2012 at 8:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.