简体   繁体   English

Python异常处理 - 使用字符串消息引发的异常,不包括字符列表

[英]Python Exception Handling - exception raised with a string message, excepted as list of characters

I am trying to raise and except a custom exception with a message, but the message string prints as tuple of characters. 我试图提出一个消息的自定义异常,但消息字符串打印为字符元组。 My error class: 我的错误类:

class myError(Exception):
    def __init__(self, arg):
        self.args = arg

And try-raise-except part : 尝试加注 - 除了部分:

try:
    raise myError('some message.')
except myError, e:
    print e.args

This when raised properly, prints:` 当正确抬起时,打印:`

('s', 'o', 'm', 'e', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e', '.', ' ')

Of course, I wanted 'some message. 当然,我想要一些消息。 '. ”。 What is going on? 到底是怎么回事?

You Don't need to declare __init__ in Your Exception: 您不需要在您的例外中声明__init__

>>> class myError(Exception):
...     pass

>>> raise myError('some message.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.myError: some message.

Your problem is that args is already a member of Exception , and it is defined as: 您的问题是args已经是Exception的成员,它被定义为:

args ARGS
The tuple of arguments given to the exception constructor 赋予异常构造函数的参数元组

So you assign a tuple with an iterable (a string is an iterable of characters) and end with a tuple of characters. 所以你给一个带有iterable的元组(一个字符串一个可迭代的字符),并以一个字符元组结束。

How to fix: 怎么修:

  1. just use args from Exception: 只使用Exception中的args

     class myError(Exception): pass try: raise myError('message') except myError as e: print(e.args[0]) 
  2. use a new member name: 使用新成员名称:

     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.

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