您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

带有错误代码和错误消息的自定义Python异常

带有错误代码和错误消息的自定义Python异常

这是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]))
python 2022/1/1 18:32:17 有223人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶