如果未引发异常,则执行

2024-05-21 02:45:35 发布

您现在位置:Python中文网/ 问答频道 /正文

如果抛出异常而不是异常,我有一些代码要执行。

目前我正在做的是:

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

这个可以改进吗?这是最好的方法吗?

更新0

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.


Tags: orofthe代码selfreturniftime
2条回答
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

您的代码表明,如果发生异常,您不想捕获它,所以为什么不简单地

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

(我遗漏了什么吗?)

相关问题 更多 >