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

6
在执行下面的代码时,如果由于某种原因无法获取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   
2个回答

6

这是因为您在使用raise时没有提供异常类型或实例。

根据文档

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

请注意,在except块中使用未带参数的raise可以重新引发异常。
FYI,在Python3中,它会引发一个RuntimeError
>>> raise
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: No active exception to reraise

4
请注意,如果您在处理异常的catch块中,则允许不带参数地使用raise

如果您需要确定是否引发了异常但不打算处理它,则可以使用更简单的raise语句重新引发异常:

>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print 'An exception flew by!'
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere

请注意,如果在expect块中调用的方法清除了异常信息,则不带参数执行raise将再次导致exceptions must be…异常。因此,使用except … as显式地将异常赋值给变量更加安全:

(本段内容来源于文档中的触发异常一节。)

try:
    raise NameError('HiThere')
except NameError as e:
    log_and_clear_exception_info('An exception flew by!')
    raise e

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接