Search code examples
pythonpython-3.xcustom-exceptions

TypeError when calling custom exception


I'm trying to throw a custom error when incorrect input is used to create an object, but am getting this error when trying to raise the exception.

TypeError: exceptions must derive from BaseException

Here is the relevant code I'm working with

def UnitError(Exception):
    pass

def ValueError(Exception):
    pass

class Temperature():

    def __init__(self, temp = 0.0, unit = 'C'):

        if type(temp) != int:
            raise ValueError('TEST') #ERROR occurs here
        else:
            self.t = float(temp)

        self.u = unit.upper()

I've never come across this error when raising custom exceptions before, could someone explain what's going on here, and how I could fix it?


Solution

  • Your "exceptions" are functions, not classes.

    Rewrite them in the following way:

    class UnitError(Exception):
        pass