这是Exception
带有特殊代码的自定义类的快速示例:
class ErrorWithCode(Exception):
def __init__(self, code):
self.code = code
def __str__(self):
return repr(self.code)
try:
raise ErrorWithCode(1000)
except ErrorWithCode as e:
print("Received error with code:", e.code)
由于您正在询问使用方法,因此args
这里有一个附加示例…
class ErrorWithArgs(Exception):
def __init__(self, *args):
# *args is used to get a list of the parameters passed in
self.args = [a for a in args]
try:
raise ErrorWithArgs(1, "text", "some more text")
except ErrorWithArgs as e:
print("%d: %s - %s" % (e.args[0], e.args[1], e.args[2]))