Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเขียน Custom Python Exceptions พร้อม Error Codes และ Messages

1. Custom Exception พร้อม Error Code

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)

ผลลัพธ์

Received error with code: 401

2. Custom Exception พร้อม Arguments, Code, Message

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

ผลลัพธ์

403: foo , bar