Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error exception must derive from BaseException even when it does (Python 2.7)

Tags:

python

What's wrong with the following code (under Python 2.7.1):

class TestFailed(BaseException):     def __new__(self, m):         self.message = m     def __str__(self):         return self.message  try:     raise TestFailed('Oops') except TestFailed as x:     print x 

When I run it, I get:

Traceback (most recent call last):   File "x.py", line 9, in <module>     raise TestFailed('Oops') TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType 

But it looks to me that TestFailed does derive from BaseException.

like image 268
James Kanze Avatar asked Oct 31 '11 17:10

James Kanze


People also ask

Does exception derive from BaseException?

The Python "TypeError: exceptions must derive from BaseException" occurs when we raise an exception that is not an instance of a class that inherits from the built-in Exception class. To solve the error, use a built-in error class, e.g. raise ValueError('message') or define your own.

What is BaseException in Python?

The BaseException is the base class of all other exceptions. User defined classes cannot be directly derived from this class, to derive user defied class, we need to use Exception class. The Python Exception Hierarchy is like below. BaseException.

How exceptions are defined in Python?

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

How do you raise an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.


2 Answers

__new__ is a staticmethod that needs to return an instance.

Instead, use the __init__ method:

class TestFailed(Exception):     def __init__(self, m):         self.message = m     def __str__(self):         return self.message  try:     raise TestFailed('Oops') except TestFailed as x:     print x 
like image 125
Raymond Hettinger Avatar answered Sep 19 '22 05:09

Raymond Hettinger


Others have shown you how to fix your implementation, but I feel it important to point out that the behavior you are implementing is already the standard behavior of exceptions in Python so most of your code is completely unnecessary. Just derive from Exception (the appropriate base class for runtime exceptions) and put pass as the body.

class TestFailed(Exception):     pass 
like image 21
kindall Avatar answered Sep 20 '22 05:09

kindall