线程异常。。。为什么它总是忽略pass关键字?

2024-04-24 08:11:43 发布

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

我被一个与线程相关的Python问题困住了。你知道吗

import threading
import time
import random
import sys
import echo

class presence(threading.Thread):

    def __init__(self, cb):
        threading.Thread.__init__(self)
        self.callback = cb

    def run(self):
        minValue = 0
        maxValue = 3

        try:
            while True:
                time.sleep(1)
                if random.randint(minValue, maxValue) == 1:
                    self.callback(1)
                elif random.randint(minValue, maxValue) == 2:
                    raise Exception('An error')
                else:
                    self.callback(0)
        except:
            print 'Exception caught!'
            pass

def showAlert():
    echo.echo('Someone is behind the door!')

def count(x):
        if x == 1:
            showAlert()
        sys.stdout.flush()

这就是我所说的:

t2 = presence.presence(presence.count)
t2.start()

我最终得到一个"Exception caught!",但是线程不再返回警报。你知道吗

我做错什么了?你知道吗


Tags: importechoselftimedefsyscallbackexception
1条回答
网友
1楼 · 发布于 2024-04-24 08:11:43

try/except块应该在循环内。例如:

while True:
    ...
    elif random.randint(minValue, maxValue) == 2:
        try:
            raise Exception('An error')
        except Exception:
            print 'Exception caught!'

否则,当引发异常并且Python跳转到except:块以处理它时,循环将退出。你知道吗

您也会注意到,我在示例中有选择地放置了try/except块,以便只覆盖可能实际引发异常的代码。这是一个最佳实践,我建议您在代码中使用它。用一个try/except块包含大部分代码会降低可读性,也会浪费空间(很多行不必要地缩进)。你知道吗

相关问题 更多 >