如何编写具有错误代码和错误消息的自定义Python异常?
我们可以编写具有错误代码和错误消息的自定义异常类,如下所示:
class ErrorCode(Exception):
def __init__(self, code):
self.code = code
try:
raise ErrorCode(401)
except ErrorCode as e:
print "接收到代码错误:", e.code
我们得到输出
C:/ Users / TutorialsPoint1 /〜.py
接收到代码错误: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
更多Python相关文章,请阅读:Python 教程
极客教程