下面的代碼給我的問題:嘗試和除了返回錯誤,但是當沒有運行時,沒有發生錯誤?
def connect(self):
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===ATTEMPTING TO CONNECT TO SERVER\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
try:
s.connect((host,port))
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===CONNECTED TO SERVER\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
self.conn=True
print("Connected")
except ConnectionRefusedError:
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===SERVER COULD NOT BE FOUND\n" + "===PLEASE MAKE SURE THE SERVER IS ON, AND YOU'RE CONNECTED TO THE NETWORK\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
else:
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===THERE'S AN ERROR WITH THE PROGRAM\n" + "===PLEASE TURN IT OFF AND ON AGAIN\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
當我連接到服務器,它既連接(「試試看」的部分完成精細,打印語句時)但是「其他」部分也會發生。我似乎無法找到原因。有誰知道這是什麼原因?
編輯:我應該說,當我刪除「其他:」部分,它也可以很好地工作。
避免使用裸'except' - 它會捕獲像'SystemExit'和'KeyboardInterrupt'這樣的東西,你可能不想捕獲它。相反,使用'except Exception'來捕獲所有剩餘的異常。 – kindall
感謝你們倆。回答了這個問題,並得到了巨大的幫助。 – QuarterGeekster