我的问题似乎很简单,但我没有找到任何帖子来解决这个问题。我需要自己的自定义异常类派生自ValueError打印预期类型(标准错误味精)以及输入的类型(与自定义文本)。Python:从ValueError派生的自定义异常类
class MyOwnException(ValueError):
def __init__(self, value):
self.value = value
print "Error: Expected type", type(self.value) #int
print "Error type", self.value #how to return expected value type?
try:
int('str')
except ValueError as e:
raise MyOwnException(e)
我非常appreatiate任何这方面的帮助:
class MyOwnException(ValueError):
...
try:
raise MyOwnException (int('str')) #not sure what to do here, as I only want to
#raise the exception if incorrect value type
except MyOwnException as e:
print "Error: Expected type", e.expType() #int
print "Error: Entered type", e.entType() #string
要通过内建的ValueError异常添加到上面,提高我的自定义异常。非常感谢! 干杯,曼纽尔
谁会提出错误?你的例子不起作用,因为int是一个内建类,不知道你的自定义异常。异常不会自动发生,因为有意识的决定,每个异常都会“手动”提出。 – 2012-02-26 14:55:49
这甚至没有帮助。 'int'可以接受一个字符串。没有“预期”类型,因为python不是静态语言。 'int('5')'就好了 – Daenyth 2012-02-26 15:05:37