[Tutor] custom error classes: how many of them does one need?

Albert-Jan Roskam fomcl at yahoo.com
Thu Jul 4 21:40:54 CEST 2013


Hello,

I created a custom error class like under [A] below (see http://pastebin.com/JLwyPsRL if you want to see highlighted code). Now I am thinking: is this specific enough? "When
creating a module that can raise several distinct errors, a common practice is
to create a base class for exceptions defined by that module, and subclass that
to create specific exception classes for different error conditions" (http://docs.python.org/2/tutorial/errors.html)
Given that I have many retcodes, is it a better approach to define a class factory that generates a custom exception for each retcode on-the-fly? (under [B]). Using a class factory seems a little unusual, or isn it? More generally: what criteria should one follow when distinguishing error classes?



global retcodes
retcodes = {0: "OK", 1: "Error_X", 2: "Error_Y"}

#############################
# [A] one custom exception for all purposes, but with a descriptive message
#############################

class single_custom_exception(Exception):
    def __init__(self, retcode, message):
        self.retcode = retcode
        message += " [%s]" % retcodes.get(retcode)
        Exception.__init__(self, message)

#############################
# [B] generating custom exceptions with a class factory
#############################

class BaseError(Exception): pass

def throw(retcode, message):
    """class factory that generates an error class for
    each return code label"""
    class custom_exception(BaseError):
        def __init__(self):
            BaseError.__init__(self, message)
    exception = retcodes.get(retcode)
    custom_exception.__name__ = exception
    return custom_exception

#######
# demonstrate use
#######

def someFunc(scenario):
    """a nonsensical function"""
    retcode = 1
    if retcode > 0:
        message = "error calling %r" % someFunc.__name__
        if scenario == "[A]":
            raise single_custom_exception(retcode, message)
        elif scenario == "[B]":
            raise throw(retcode, message)

>>> someFunc("[A]")
Traceback (most recent call last):
  File "/home/antonia/Desktop/tutor.py", line 44, in <module>
    someFunc("[A]")
  File "/home/antonia/Desktop/tutor.py", line 40, in someFunc
    raise single_custom_exception(retcode, message)
single_custom_exception: error calling 'someFunc' [Error_X]


>>> someFunc("[B]")
Traceback (most recent call last):
  File "/home/antonia/Desktop/tutor.py", line 44, in <module>
    someFunc("[B]")
  File "/home/antonia/Desktop/tutor.py", line 42, in someFunc
    raise throw(retcode, message)
Error_X: error calling 'someFunc'


# this may be useful
print issubclass(throw(1, "some message"), BaseError)  # returns True

 
Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


More information about the Tutor mailing list