Execute if no exception is thrown

I have some code that I want to do, if the exception does not .

I am currently doing this:

try:
    return type, self.message_handlers[type](self, length - 1)
finally:
    if not any(self.exc_info()):
        self.last_recv_time = time.time()

Can this be improved? Is this the best way to do this?

Update0

The optional else clause is executed if and when control flows to the end of the try clause.

Currently, control is flowing from the end, unless the return, continue, or break statement is excluded or executed.

+5
source share
2 answers

Your code tells you that you don’t want to catch an exception if it occurs, so why not just

result = type, self.message_handlers[type](self, length - 1)
self.last_recv_time = time.time()
return result

(I didn’t miss anything?)

+8
try:
   tmp = type, self.message_handlers[type](self, length - 1)
except Exception:
   pass #or handle error, or just "raise" to re-raise
else:
   self.last_recv_time = time.time()
   return tmp
+12

All Articles