Python try和except以及线程出错

Python try和except以及线程出错,python,multithreading,try-catch,Python,Multithreading,Try Catch,我已经用线程写了一个程序。下面是我编写的代码示例: from time import sleep, time from threading import Thread def UserInfo(): global gamesummary Thread(target = CheckTime).start() gamesummary=open("gamesummary.txt","w+") AskQuestions() def CheckTime(): g

我已经用线程写了一个程序。下面是我编写的代码示例:

from time import sleep, time
from threading import Thread

def UserInfo():
    global gamesummary
    Thread(target = CheckTime).start()
    gamesummary=open("gamesummary.txt","w+")
    AskQuestions()

def CheckTime():
    global gamesummary
    sleep(5)
    print("Time's up!")
    gamesummary.close()
    raise ValueError

def AskQuestions():
    global gamesummary
    try:
        while True:
            input("Program asks questions correctly here: ")
            gamesummary.write("Program correctly records information here")
    except ValueError:
        EndProgram()

def EndProgram():
    end=input("Would you like to play again?: ")

    if(end.lower()=="yes"):
        UserInfo()
    elif(end.lower()=="no"):
        print("Thank you for playing.")
        sleep(1)
        raise SystemExit
    else:
        print("Please enter either 'yes' or 'no'.\n")
        EndProgram()
程序中的所有操作都已正确完成并正常继续,但此错误在EndProgram()之前显示:

此错误不会停止程序的运行


我不明白为什么try-and-except语句没有捕获这个异常。我想这是因为我制造了两个错误?我不熟悉使用python,我非常感谢您对我的帮助。

在后台线程中出现
ValueError
的原因是您在该线程的目标函数中显式地引发了
ValueError

def CheckTime():
    global gamesummary
    sleep(5)
    print("Time's up!")
    gamesummary.close()
    raise ValueError
当后台线程引发异常时,它不会杀死整个程序,而是将回溯转储到stderr并杀死线程,让其他线程继续运行。这就是你在这里看到的

如果你不想那样,那就别插嘴

如果您希望异常会以某种方式影响主线程,那么它不会这样做。但你不需要它来做那件事。您正在从主线程下关闭文件,这意味着
AskQuestions
将在关闭的文件上获得
ValueError:I/O操作
异常,当它尝试
写入文件时。你处理得很好。这是一个有点奇怪的设计,但它会按预期工作;你不需要在上面加任何额外的东西

如果您希望从主线程捕获异常,那么这也不会起作用,但同样,它是不需要的。主线程不受后台线程异常的影响

def CheckTime():
    global gamesummary
    sleep(5)
    print("Time's up!")
    gamesummary.close()
    raise ValueError