args, an attribute of exception
When an exception occurs, it may have associated values, also known as the exception’s arguments.
The except clause may specify a variable after the exception name. The variable is bound to the exception instance which typically has an args
attribute that stores the arguments. For convenience, builtin exception types define __str__()
to print all the arguments without explicitly accessing .args
也就是说,当我们打印一个异常的时候,实际发生了如下调用
print -> exception.__str__() -> exception.args
>>>
try:
raise Exception('spam', 'eggs')
except Exception as inst:
print(type(inst)) # the exception type
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
# but may be overridden in exception subclasses
x, y = inst.args # unpack args
print('x =', x)
print('y =', y)
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
The exception’s __str__()
output is printed as the last part (‘detail’) of the message for unhandled exceptions.
how to define customed exception
两个关键方法:__init__()
__str__()
关于 自定义异常 的__init__()
如果你想定义的新异常重写了 __init__()
方法, 确保你使用所有参数调用 Exception.__init__()
,例如:
class CustomError(Exception):
def __init__(self, message, status):
super().__init__(message, status)
self.message = message
self.status = status
Exception的默认行为是接受所有传递的参数并将它们以元组形式存储在 .args
属性中. 很多其他函数库和部分Python库默认所有异常都必须有 .args
属性, 因此如果你忽略了这一步,你会发现有些时候你定义的新异常不会按照期望运行
只有显式地调用super().__init__()
给自定义异常实例的.args
属性赋值,后续打印异常时__str__()
方法才有内容可用
当然,如果你想改变异常打印的内容样式,重写__str__()
即可
网友评论