码迷,mamicode.com
首页 > 其他好文 > 详细

处理异常的两种写法

时间:2017-04-23 15:53:17      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:exce   style   nbsp   except   lib   port   att   led   open   

 1 from urllib.request import Request, urlopen
 2 from urllib.error import URLError, HTTPError
 3 req = Request(someurl)
 4 try:
 5     response = urlopen(req)
 6 except HTTPError as e:
 7     print(The server couldn\‘t fulfill the request.)
 8     print(Error code: , e.code)
 9 except URLError as e:
10     print(We failed to reach a server.)
11     print(Reason: , e.reason)
12 else:
13 # everything is fine
 1 from urllib.request import Request, urlopen
 2 from urllib.error import URLError
 3 req = Request(someurl)
 4 try:
 5     response = urlopen(req)
 6 except URLError as e:
 7     if hasattr(e, reason):
 8         print(We failed to reach a server.)
 9         print(Reason: , e.reason)
10     elif hasattr(e, code):
11         print(The server couldn\‘t fulfill the request.)
12         print(Error code: , e.code)
13 else:
14 # everything is fine

 

处理异常的两种写法

标签:exce   style   nbsp   except   lib   port   att   led   open   

原文地址:http://www.cnblogs.com/themost/p/6752596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!