Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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]")
- someFunc("[B]")
- # this may be useful
- print issubclass(throw(1, "some message"), BaseError) # returns True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement