繁体   English   中英

调用自定义异常时出现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()

之前提出自定义异常时,我从来没有遇到过此错误,有人可以解释这里发生了什么,以及我该如何解决?

您的“例外”是函数,而不是类。

用以下方式重写它们:

class UnitError(Exception):
    pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM