Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để viết ngoại lệ Python tùy chỉnh với Mã lỗi và Thông báo Lỗi?

Chúng ta có thể viết các lớp ngoại lệ tùy chỉnh với mã lỗi và thông báo lỗi 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 tôi nhận được đầu ra

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

Chúng tôi cũng có thể viết các ngoại lệ tùy chỉnh với các đối số, mã lỗi và thông báo lỗi 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 tôi nhận được kết quả sau

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