使用try和Python除外时如何仍然显示错误消息

问题描述

在我的Python代码中,我有一个带有“ try”和“ except”语句的函数:

        for x in range (int(firstSocketEntry.get()),int(lastSocketEntry.get())+1): # Test will be done according to the range of the sockets
            for attempt in range (int(attemptEntry.get())):
                try:
                    print('Attempt: ' + str(attempt+1))
                    print('DUT: ' + str(x))
                    time.sleep(1)
                    client = HTTPClient('http://' + ipEntry.get() + port)
                    response = client.send(Request('test_is_alive',x),timeout=httpTimeOutEntry.get())
                    # response = request("http://" + ipEntry.get() + port,"test_is_alive",x)
                    time.sleep(1)
                    print(response.text)
                    print(response.data.result)
                    answer = response.data.result
             
                    logFile.write(time.strftime("%Y_%m_%d-%H_%M_%S\t\t") + str(x) + "\t\t" + str(answer) + "\t\t" + str(readVoltage()) + "\t\t" + str(readCurrent()) + "\n")               
                
                except:
                    print("Something went wrong!")
                    executeFunctionX()

                    
                else:
                    if (response.data.result==False):
                        print("\nAttempt " + str(attempt + 1) + " failed!")
                    else:
                        break
            else:
                print('\nAll attempts failed!')

如果现在“ try”语句中的某些地方出了问题,那么代码将继续执行“ except”语句,这就是目标。 我仍然如何获得错误消息(即:

回溯(最近通话最近): 文件“ C:\ Users \ pfra \ AppData \ Local \ Programs \ P six.raise_from(e,无) 在第三行中的“ _”文件“” 文件“ C:\ Users \ pfra \ AppData \ Local \ Programs \ P httplib_response = conn.getresponse())?

因为现在,我不知道到底出了什么问题。

我们非常感谢您的帮助。非常感谢。 问候

解决方法

您将需要稍微修改except:

看到这个:

>>> try:
...     a
... except:
...     print("Something went wrong!")
... 
Something went wrong!

并与以下内容进行比较:

>>> try:
...     a
... except NameError as e:
...     print(f"What went wrong is {e}")
... 
What went wrong is name 'a' is not defined

如果您不知道代码可能引发什么异常,则可以使用except Exception as e:。但是,花一些时间来了解您的代码可能引发哪些异常是很有意义的。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...