[英]Exception handling in python Counting the number of characters in a string
[英]Python Exception Handling - exception raised with a string message, excepted as list of characters
我试图提出一个消息的自定义异常,但消息字符串打印为字符元组。 我的错误类:
class myError(Exception):
def __init__(self, arg):
self.args = arg
尝试加注 - 除了部分:
try:
raise myError('some message.')
except myError, e:
print e.args
当正确抬起时,打印:`
('s', 'o', 'm', 'e', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e', '.', ' ')
当然,我想要一些消息。 ”。 到底是怎么回事?
您不需要在您的例外中声明__init__
:
>>> class myError(Exception):
... pass
>>> raise myError('some message.')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.myError: some message.
您的问题是args
已经是Exception
的成员,它被定义为:
ARGS
赋予异常构造函数的参数元组
所以你给一个带有iterable的元组(一个字符串是一个可迭代的字符),并以一个字符元组结束。
怎么修:
只使用Exception中的args
:
class myError(Exception): pass try: raise myError('message') except myError as e: print(e.args[0])
使用新成员名称:
class myError(Exception): def __init__(self, arg): self.msg = arg try: raise myError('message',) except myError as e: print(e.msg)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.