Custom Python Exceptions with Error Codes and Error Messages

后端 未结 2 1714
灰色年华
灰色年华 2020-12-13 00:29
class AppError(Exception):
    pass

class MissingInputError(AppError):
    pass

class ValidationError(AppError):
    pass

...

def v         


        
2条回答
  •  不思量自难忘°
    2020-12-13 00:36

    Here's a quick example of a custom Exception class with special codes:

    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)
    

    Since you were asking about how to use args here's an additional example...

    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]))
    

提交回复
热议问题