以下代码给出了我的问题:
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)
当我连接到服务器时,它都连接(“try”部分完成,打印声明发生)但是也会出现“else”部分。我似乎无法找到原因。有没有人知道造成这种情况的原因是什么?
编辑:我应该说当我删除“else:”部分时,它也可以正常工作。
答案 0 :(得分:1)
我猜你在这里试图捕捉所有异常,但这不是正确的语法。
正确的方法是:
try:
# do something dangerous
except ConnectionRefusedError:
# handle known error
except:
# handle unknown error
在这种情况下, else
表示如果没有错误发生,代码将被执行。
答案 1 :(得分:1)
else
块的try: except: else: finally:
部分与else
中的if: else:
类似,有效:
if someerror:
...
else:
...
当{em>没有从else
块中引发错误时,try
块会运行。使用此块可以最小化try
块中的代码;在你的情况下:
try:
s.connect((host,port))
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, ("===CONNECTED TO SERVER\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
self.conn=True
print("Connected")