我怎么知道 "except urllib2.URLError, e" 中是否有 e

How can I figure whether to have e in "except urllib2.URLError, e"

我在查看 urllib2 时得到了这段代码。

import urllib2
req = urllib2.Request('http://www.baibai.com')
try: urllib2.urlopen(req)
except urllib2.URLError,e: 
    print e.reason

我很困惑何时以及是否在语句 except urllib2.URLError, e: 中使用 e 因为使用 except urllib2.URLError: 似乎没问题(没有 e)。

是否每个 except 语句都具有格式 except:XXXX, e 或仅在某些情况下?

使用语法 urllib2.URLError, e 您可以访问抛出的异常(例如打印消息)。如果你只使用 except urllib2.URLError 你表示你想在抛出 URLError 时做一些事情,但你不需要实际的异常对象。

请注意,您使用的是过时的 python 版本,因为您在 except 块中使用 ,。 Python 3+ 需要 as 而不是 , (except urllib2.URLError as e) 而只有 Python 2.5- 使用 , 语法。

我建议您了解一下异常。 Here's the official documentation on exceptions. More information about , vs as can be found on this Whosebug 答案。