Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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   
like image 912
Venu Avatar asked Dec 12 '14 07:12

Venu


2 Answers

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
like image 90
alecxe Avatar answered Oct 17 '22 08:10

alecxe


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
like image 42
Dag Høidahl Avatar answered Oct 17 '22 10:10

Dag Høidahl