Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách viết custom Python Exceptions với Error Codes và Error Messages?

Chúng ta có thể viết custom exception classes với error codes và error messages như sau:

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)

Chúng ta nhận được output:

C:/Users/TutorialsPoint1/~.py Received error with code: 401

Chúng ta cũng có thể viết custom exceptions với arguments, error codes và error messages như sau:

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

Chúng ta nhận được output sau:

C:/Users/TutorialsPoint1/~.py 403: foo , bar