异常必须是旧式类或派生自BaseException,而不是NoneType

Ven*_*enu 6 python exception python-2.7

在执行下面的代码时,如果因某些原因无法获取firefox配置文件/ webdriver,则会出现以下错误:

异常必须是旧式类或派生自BaseException,而不是NoneType

我想了解为什么在这种情况下会显示此错误:

self.error = 0  
self.profile, profileErrStatus = self.GetFireFoxProfile(path)
if self.profile:
  self.driver, driverErrStatus = self.GetFireFoxWebDriver(self.profile)
  if self.driver:
  else:
    print('Failed to get Firefox Webdriver:%s'%(str(sys.exc_info()[0])))
    raise
else:
  print('Failed to get Firefox Profile:%s'%(str(sys.exc_info()[0])))
  raise   
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 5

这是因为您在raise不提供异常类型或实例的情况下使用.

根据文件:

提出的唯一论据表明要提出的例外.这必须是异常实例或异常类(派生自Exception的类).

演示:

>>> raise
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType

>>> raise ValueError('Failed to get Firefox Webdriver')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Failed to get Firefox Webdriver
Run Code Online (Sandbox Code Playgroud)

请注意,raise可以在except块内部使用不带参数来重新引发异常.


仅供参考,在python3上,它会引发一个RuntimeError反而:

>>> raise
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: No active exception to reraise
Run Code Online (Sandbox Code Playgroud)