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

标签 python python-2.7 exception

在执行下面的代码时,如果由于某种原因无法获取 firefox 配置文件/webdriver,我会收到以下错误消息:

exceptions must be old-style classes or derived from BaseException, not 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   

最佳答案

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

根据documentation :

The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from 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 block 中使用不带参数的 raise 来重新引发异常。


仅供引用,在 python3 上,它会引发 RuntimeError 而不是:

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

关于python - 异常必须是旧式类或派生自 BaseException,而不是 NoneType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27438986/

相关文章:

python - Python 中的组合学

bash - 将多个 CSV 行与大多数空字段合并为每个时间戳的单行

java - 修复错误 : Unreported Exception InterruptedException

list - 如何在字典列表中向字典添加键?

python - 如何检查行是否只包含数字?

Visual Studio Code 中的 PHP 调试会在每次异常时中断

java - "NoClassDefFoundError: Could not initialize class"错误

python - 如何在 Spark SQL 中压缩两个数组列

python - 保存和恢复扩展窗口小部件的位置和大小

python - 关闭文件以便我可以在 Windows 上用 Python 删除它?