可使用 except: 捕获任何异常,包括 SystemExit 和 KeyboardInterupt,不过这样不便于程序的调试和使用socket
最简单的状况是捕获 urllib2.URLErrorurl
try: urllib2.urlopen("http://example.com", timeout = 1) except urllib2.URLError, e: raise MyException("There was an error: %r" % e)
如下代码对超时异常进行了捕获spa
import urllib2 import socket class MyException(Exception): pass try: urllib2.urlopen("http://example.com", timeout = 1) except urllib2.URLError, e: if isinstance(e.reason, socket.timeout): raise MyException("There was an error: %r" % e) else: # reraise the original error raise