11

I have some code I want to execute if an exception is not thrown.

Currently I'm 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 on? Is this the best way to do it?

Update0

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

Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
  • Maybe I understand this wrong... but if you `return` something without exception, how can you execute anything afterwards within this method? – eumiro Aug 02 '11 at 12:43

2 Answers2

28
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
Thomas K
  • 39,200
  • 7
  • 84
  • 86
9

Your code suggests that you don't want to catch the exception if it occurs, so why not simply

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

(Am I missing anything?)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841