简体   繁体   中英

exceptions must be old-style classes or derived from BaseException, not NoneType

On executing below code I get below error if it fails to get firefox profile/webdriver for some reason:

exceptions must be old-style classes or derived from BaseException, not NoneType

I want to understand why this error is displayed in this case:

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   

This is because you are using raise without providing an exception type or instance.

According to the 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).

Demo:

>>> 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

Note that raise without arguments can be used inside an except block to re-raise an exception.


FYI, on python3, it would raise a RuntimeError instead:

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

Note that raise without an argument is allowed if you are in a catch block with an exception currently handled:

If you need to determine whether an exception was raised but don't intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

>>> 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

(From Raising Exceptions in the documentation.)

Beware, though, that if a method called in the expect block clears the exception info, raise without an argument will result in the exceptions must be… exception again. So explicitly assigning the exception to a variable with except … as is safer:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM