Advertisement
Guest User

Untitled

a guest
Jul 4th, 2013
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. global retcodes
  2. retcodes = {0: "OK", 1: "Error_X", 2: "Error_Y"}
  3.  
  4. #############################
  5. # [A] one custom exception for all purposes, but with a descriptive message
  6. #############################
  7.  
  8. class single_custom_exception(Exception):
  9.     def __init__(self, retcode, message):
  10.         self.retcode = retcode
  11.         message += " [%s]" % retcodes.get(retcode)
  12.         Exception.__init__(self, message)
  13.  
  14. #############################
  15. # [B] generating custom exceptions with a class factory
  16. #############################
  17.  
  18. class BaseError(Exception): pass
  19.  
  20. def throw(retcode, message):
  21.     """class factory that generates an error class for
  22.    each return code label"""
  23.     class custom_exception(BaseError):
  24.         def __init__(self):
  25.             BaseError.__init__(self, message)
  26.     exception = retcodes.get(retcode)
  27.     custom_exception.__name__ = exception
  28.     return custom_exception
  29.  
  30. #######
  31. # demonstrate use
  32. #######
  33.  
  34. def someFunc(scenario):
  35.     """a nonsensical function"""
  36.     retcode = 1
  37.     if retcode > 0:
  38.         message = "error calling %r" % someFunc.__name__
  39.         if scenario == "[A]":
  40.             raise single_custom_exception(retcode, message)
  41.         elif scenario == "[B]":
  42.             raise throw(retcode, message)
  43.  
  44. someFunc("[A]")
  45. someFunc("[B]")
  46.  
  47. # this may be useful
  48. print issubclass(throw(1, "some message"), BaseError)  # returns True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement