我正在编写一个程序,该程序的一部分从文件中下载数据,尤其是浮点数。我使用except来将字符串转换为float时捕获错误,但是发生异常时会发生奇怪的事情。我的代码只有一部分执行,在这种情况下,sys.exit(1)
,infoBox.setText
被完全省略。我不知道为什么会发生这种情况,非常感谢您的帮助。这是代码:
def on_click_load(self):
with open('parameters.txt', 'r', encoding='utf-8') as file:
a = file.read()
help_tab = []
# Pipe along with O, x are special markers in file
for i in range(len(a) - 3):
if a[i] == '|' and a[i + 1] == 'O' and a[i + 2] == 'x':
while a[i + 3] != '|':
if a[i + 3].isdigit() == True:
help_tab.append(a[i + 3])
elif a[i + 3] == '.' or a[i + 3] == '-':
help_tab.append(a[i + 3])
else:
j = ''.join(help_tab)
try:
self.TabX.append(float(j))
except ValueError:
# I have problem in this section
self.infoBox.setText(
'There is an error in data in input file . The window will close in 3 seconds')
QTimer.singleShot(3000, lambda: sys.exit(1))
help_tab.clear()
i += 1
答案 0 :(得分:1)
您可以尝试
except Exception as e:
print (f'{type(e)}: {e}')
找出错误的类型和错误的类型,以便您可以查看错误消息并从此处进行调试。
此外,您可以通过在每个部分的前后添加打印语句来找出问题所在。
示例:
try:
print ('start')
self.TabX.append(float(j))
print ('append succeed ' + str(float(j))
except Exception as e:
print (f'{type(e)}: {e}')
print ('entered')
self.infoBox.setText('There is an error in data in input file . The window will close in 3 seconds')
print ('next')
QTimer.singleShot(3000, lambda: sys.exit(1))
print ('end')