Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have an application App with error codes and error messages like this in the code below.

class AppError(Exception): pass
class BlahBlahError(AppError):
# definition of the error codes & messages
messerr = {101: " Certain error here. Please verify.", \
102: “Another one here. Please verify.", \
103: "One more here. Please verify.", \
104: "That was a bloomer!. Please verify."}

How do I write custom python exceptions with error codes and error messages?


1 Answer
Rajendra Dharmkar

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.