如何编写带有错误代码和错误消息的自定义 Python 异常?
我们可以编写带有错误代码和错误消息的自定义异常类,如下所示
class ErrorCode(Exception): def __init__(self, code): self.code = code try: raise ErrorCode(401) except ErrorCode as e: print "Received error with code:", e.code
我们获得输出
C:/Users/TutorialsPoint1/~.py Received error with code: 401
我们还可以编写带有参数、错误代码和错误消息的自定义异常,如下所示
class ErrorArgs(Exception): def __init__(self, *args): self.args = [a for a in args] try: raise ErrorArgs(403, "foo", "bar") except ErrorArgs as e: print "%d: %s , %s" % (e.args[0], e.args[1], e.args[2])
我们得到以下输出
C:/Users/TutorialsPoint1/~.py 403: foo , bar
广告