在 Python 2.7.x 中,我创建了一个异常类:
class myException(RuntimeError):
def __init__(self,arg):
self.args = arg
当我使用它时:
try:
raise myException("This is a test")
except myException as e:
print e
打印出来是这样的:
('T', 'h', 'i', 's', ' ', 'i', 's'...)
我没有打印整个东西,但为什么没有打印成字符串?我该如何转换它?
还有,为什么e.message是空白的?
请您参考如下方法:
args 异常是特殊的;它期望是一个序列。将 string 分配给 self.args 是合法的,它是一个序列,但是当您这样做时它会被转换为一个元组。
改为分配一个包含您的参数的元组:
class myException(RuntimeError):
def __init__(self, arg):
self.args = (arg,)
参见 BaseException documentation :
args
The tuple of arguments given to the exception constructor. Some built-in exceptions (likeIOError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.
