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:
>>> 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
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.
How to fix:
just use args
from Exception:
class myError(Exception): pass try: raise myError('message') except myError as e: print(e.args[0])
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.