尝试和除了返回错误,但是当没有运行时,没有错误发生?

时间:2014-02-19 15:34:29

标签: python tkinter try-catch

以下代码给出了我的问题:

    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:”部分时,它也可以正常工作。

2 个答案:

答案 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")