How to write custom Python Exceptions with Error Codes and Error Messages?

PythonServer Side ProgrammingProgramming

We can write custom exception classes with error codes and error messages as follows:

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

We get output

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

We can also write custom exceptions with arguments, error codes and error messages as follows:

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

We get following output

C:/Users/TutorialsPoint1/~.py
403: foo , bar
raja
Published on 06-Dec-2017 15:44:13
Advertisements