The error exception should come from BaseException, even if it happens (Python 2.7)

What is 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 seems to me that TestFailed comes from BaseException .

+7
source share
4 answers

__new__ is a static method that should return an instance.

Use the __init__ method instead:

 >>> 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 Oops 
+9
source

Others have shown you how to fix your implementation, but I find it important to note that the behavior you implement is already the standard exception behavior in Python, so most of your code is completely unnecessary. Just throw an Exception (the appropriate base class for runtime exceptions) and put pass in the body.

 class TestFailed(Exception): pass 
+11
source

Use __init__() instead of __new__() to “initialize” classes. In most cases, overriding __new__ not required. It is called before __init__ during object creation.

See also Using Python __new__ and __init__?

+4
source

The __new__ implementation should return an instance of the class, but currently it returns None (by default).

However, it looks like you should use __init__ here, not __new__ .

+2
source

All Articles