可以使用 except: 捕获任何异常,包括 SystemExit 和 KeyboardInterupt,不过这样不便于程序的调试和使用

最简单的情况是捕获 urllib2.URLError

try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)

以下代码对超时异常进行了捕获

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
05-23 10:51