Python 用户定义的异常怀疑

Python 用户定义的异常怀疑,python,Python,我有这个特例课 class Value(Exception): def __init__(self,val): self.val = val def __str__(self): return repr(self.val) raise Value('4') 例外情况如下 Traceback (most recent call last): File "<module1>", line 20, in <module> V

我有这个特例课

class Value(Exception):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return repr(self.val)

raise Value('4')
例外情况如下

Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'
回溯(最近一次呼叫最后一次):
文件“”,第20行,在
值:“4”
------------------------------------更新------

多亏了马克,我发现了一个打字错误。。。。但我现在的问题是,假设我想显示4和一个字符串hello以及错误,如何做到这一点


非常感谢

我想你是想在这里写
val
而不是
value

def __str__(self):
    return repr(self.val) # <--- not self.value
另一个例子:

def __str__(self):
    return "val1 = {}, val2 = {}".format(self.val1, self.val2)
当然,您可以在init中执行任何您想要的操作。。正如您在示例中所示,使用语法*val(而不是init中的val)来使用类值,然后只需调用

值(4,2)或值(4)等

编辑:

只需在repr中返回self.msg

def __repr__(self):
    return self.val + self.msg #or whatever you want
我前面的示例演示了如何接受和打印多个值……如果您只需要一个值和一个消息,并显示它们,则可以执行以下操作:

class Value(Exception):
    def __init__(self, val, msg):
        self.val = val
        self.msg = msg
    def __repr__(self):
        return 'Error code: %s  Error message: %s' % (self.val, self.msg)
    def __str__(self):
        return repr(self)
我现在的问题是,假设我想显示4和一个字符串hello,以及如何执行错误

您应该将代码放入try/except代码中以处理异常。以下是一个例子:

尝试:
如果某事:
提升值('4')
#在这里做点别的
除值作为值例外:
打印“您好,它引发值异常“%s”%”%valueException.message

val1={0.val1},val2={0.val2}。格式(self)
也可以工作。
def __repr__(self):
    return self.val + self.msg #or whatever you want
class Value(Exception):
    def __init__(self, val, msg):
        self.val = val
        self.msg = msg
    def __repr__(self):
        return 'Error code: %s  Error message: %s' % (self.val, self.msg)
    def __str__(self):
        return repr(self)
try: if something: raise Value('4') # do something else here except Value as valueException: print "Hello, it raises an Value exception '%s'" % valueException.message