尝试在tkinter中捕获异常

时间:2014-10-15 13:00:04

标签: python

我有以下代码段:

def start_server():
    try:
        global ucs2
        ucs2 = socket.socket()
        ucs2.connect(server_add)
    except Exception:
        textfield.config(state=NORMAL)
        textfield.insert(END, str(geterror())+"\n")
        textfield.config(state=DISABLED)

    else:
        textfield.config(state=NORMAL)
        textfield.insert(END, "Success!\n")
        textfield.config(state=DISABLED)
        listen()
        thread.start_new_thread(new_msg, ())
if __name__ == "__main__":

    root = Tk()
    add_widget()
    root.protocol("WM_DELETE_WINDOW", warnexit)



    root.after(3000, start_server)

    root.mainloop()

但是,如果我运行它,即使ucs2套接字引发了像ConnectionRefusedError这样的异常,它也只会在控制台上显示错误并且不会捕获它。这有什么问题?

2 个答案:

答案 0 :(得分:2)

你没有抓住ConnectionRefusedError。这样做:

except ConnectionRefusedError:

答案 1 :(得分:0)

首先,确保在try-catch块中实际抛出异常。如果是,您可以使用以下语法来捕获所有异常:

try:
    do_stuff()
except: #Catches Everything (This is usually a bad idea)
    catch_stuff()