调用自定义异常时出现TypeError
TypeError when calling custom exception
我试图在使用不正确的输入创建对象时抛出自定义错误,但在尝试引发异常时遇到此错误。
TypeError: exceptions must derive from BaseException
这是我正在使用的相关代码
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()
我以前在引发自定义异常时从未遇到过这个错误,谁能解释一下这是怎么回事,我该如何解决?
你的"exceptions"是函数,不是类。
按以下方式重写它们:
class UnitError(Exception):
pass
我试图在使用不正确的输入创建对象时抛出自定义错误,但在尝试引发异常时遇到此错误。
TypeError: exceptions must derive from BaseException
这是我正在使用的相关代码
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()
我以前在引发自定义异常时从未遇到过这个错误,谁能解释一下这是怎么回事,我该如何解决?
你的"exceptions"是函数,不是类。
按以下方式重写它们:
class UnitError(Exception):
pass