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
.
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.
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.
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.
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.
__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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With