![](/img/trans.png)
[英]exceptions must be old-style classes or derived from BaseException, not HttpResponseRedirect
[英]exceptions must be old-style classes or derived from BaseException, not NoneType
在执行下面的代码时,如果由于某种原因导致无法获取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
这是因为您在不提供异常类型或实例的情况下使用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
需要注意的是raise
不带参数可以内部的使用except
块重新抛出异常。
仅供参考,在python3上,它会引发一个RuntimeError
:
>>> raise
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: No active exception to reraise
请注意,如果您处于当前处理异常的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…
再次exceptions must be…
exception。 所以明确地将异常分配给变量, except … as
更安全:
try:
raise NameError('HiThere')
except NameError as e:
log_and_clear_exception_info('An exception flew by!')
raise e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.