Tommy
Tommy

Reputation: 1239

Python exception in exception

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.

Upvotes: 4

Views: 906

Answers (2)

Alfe
Alfe

Reputation: 59446

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.

Upvotes: 0

Paulo Scardine
Paulo Scardine

Reputation: 77281

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.

Upvotes: 5

Related Questions