简体   繁体   中英

Try/Except not catching UnboundLocalError on KeyboardInterrupt

I have a simple file transfer server that uses socket, It has an infinite listening to clients loop in the Main() func, so i surrounded it with Try/Except with KeyboardInterrupt so i would be able to properly close all the sockets and connections when CTRL+C-ing out

def Main():
    try:
        #various variable initations
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.bind((host,port))
        print 'Socket bound to host - {0} and port {1}'.format(host,port)

        sock.listen(5)

        print 'Waiting for connections...'

        while True:
            conn, addr = sock.accept()
            print 'Client IP:',str(addr)
            #getting data from client and making the server do the appropriate functions

        conn.close()        
        sock.close()
    except(KeyboardInterrupt): # redundancy to make sure that a keyboard interrupt to close the program also closes the sockets and connections
        conn.close()
        sock.close()
        print 'Manual Close'
        sys.exit()

Now when a client connects and does whatever and i close it via keyboard interrupt it works fine, printing me the 'Manual Close'

But when i close via keyboardinterrupt before a client connects it gives me this error: UnboundLocalError: local variable 'conn' referenced before assignment

I understand the conn doesn't get assigned if a client doesn't connect but i thought that any errors under except get ignored

You can just put the functions within the except block inside another try/except and tell it to ignore the exception with pass

except(KeyboardInterrupt): # redundancy to make sure that a keyboard interrupt to close the program also closes the sockets and connections
    try:
        conn.close()
        sock.close()
    except:
        pass
    print 'Manual Close'
    sys.exit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM