我用线程写了一个程序。下面是我编写的代码示例:
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(( 之前:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:UsersakeriAppDataLocalProgramsPythonPython36-32libthreading.py", line 916, in _bootstrap_inner
self.run()
File "C:UsersakeriAppDataLocalProgramsPythonPython36-32libthreading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "x-wingide-python-shell://105807224/2", line 15, in CheckTime
ValueError
此错误不会阻止程序运行。
我不明白为什么 try and except 语句没有捕获此异常。我认为这是因为我正在创建两个错误?我是使用 python 的新手,我真的很感激能得到任何帮助。
您在后台线程中获得ValueError
的原因是您在该线程的目标函数中显式引发ValueError
:
def CheckTime():
global gamesummary
sleep(5)
print("Time's up!")
gamesummary.close()
raise ValueError
当后台线程引发异常时,它不会杀死整个程序,而只是将回溯转储到 stderr 并杀死线程,让其他线程运行。这就是你在这里看到的。
如果您不想要这样,请将其保留
。如果您希望异常会以某种方式影响主线程,它不会这样做。但是你不需要它来做到这一点。您正在从主线程下关闭文件,这意味着AskQuestions
尝试write
文件时将获得ValueError: I/O operation on closed file
异常。您正在正确处理。这是一个有点奇怪的设计,但它会按预期工作;您无需在其上添加任何额外的内容。
如果您希望从主线程中捕获异常,那也不起作用 - 但同样,它不是必需的。主线程不受后台线程异常的影响。