![](/img/trans.png)
[英]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.