异常处理-做一个优雅的程序员

异常处理基本语法:

try:

except:

finally:

#!/usr/bin/env python
try:
    a=1/0
    print a
except Exception,e:
    print e

当你打开一个连接没有关闭是抛出异常,那么你可以使用finally来关闭它。

如:

#!/usr/bin/env python
#filename:con.py
import socket,sys
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
timeout=10
socket.setdefaulttimeout(timeout)

try:
    s.connect(("www.idu.com",820))
except socket.gaierror,e:
    print "Error connection to server :%s" %e
    sys.exit(1)
finally:
    s.close()

Error connection to server :[Errno -5] No address associated with hostname

 

 

posted @ 2014-05-19 12:04  UCanBeFree  阅读(115)  评论(0编辑  收藏  举报