簡體   English   中英

異常必須是舊式類或派生自BaseException,而不是NoneType

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM