Typeerror: exceptions must derive from baseexception error occurs while raising incompatible class with raise keyword. See there are many python Exception classes like ValueError, TypeError, etc which are on the top of the Exception class. While applying exceptional handling in any condition we are only permissible to use those Exception classes where the Base class is Exception.
Typeerror: exceptions must derive from baseexception ( Reason ) –
Let’s see the problem first –
num=2.8 if(type(num)==float): raise "Float is not acceptable"
Here the raise keyword is throwing the EXCEPTION. See! There are two reasons why we get this error.
1. raise any Predefine class which don’t inherit base class as Exception
2. raise any custom class which do not inherit Exception class
Typeerror: exceptions must derive from baseexception ( Solution) –
As we have already discussed the reason behind this error. In this section, we will explain the solution for them.
1. To raise any Predefine class which don’t inherit base class as Exception –
Here as the above code, we are raising the str object with the raise keyword. This is an incorrect way of handing the raise keyword. In place of that, we can use ValueError or RuntimeError. Let’s see with an example-
num=2.8 if(type(num)==float): raise ValueError("Float is not acceptable")
In the same way, we can use RuntimeException just like ValueError.
2. raise any custom class which do not inherit Exception class –
Here we will create a custom python class and then we will raise its object. Here is the code –
class my_class(): def __init__(self, m): self.text = m def __str__(self): return self.text try: raise my_class('caught') except my_class as txt: print (txt)
we my_class is not inhering Exception or baseException class. Hence while running this piece of code, we get the above error.
Now let’s inherit the Exception class and rerun the same. It will resolve the error for us.
Hope the problem is fixed now, Please write back to us with any concerns.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.