![]() class DomainException(Exception):" """Life is not what I expected"""""def process(item):" # There is no way that this item can be processed, so bail out quickly." # Here you are assuming that your caller will report this error but probably" # it will be able to process the other items." if item.foo > item.bar:" raise DomainException("bad news")"" # Everybody knows that every item has more that 10 wickets, so" # the following instruction is assumed always being successful." # But even if luck is not on our side, our caller will be able to" # cope with this situation and keep on working" item.wickets *= 2 Use such exception(s) to "bubble out" when the data you are dealing with are not what you expected or to signal inconsistent situations, while separating them from the normal standard exception arising from regular bugs or problems outside the modeled domain (IO errors etc). Tip 3: define an "application exception", eventually you may want to define a hierarchy of such exception but this is better discovered when the need arise. import logging"logger = logging.getLogger()""for item in items:" try:" process(item)" except Exception, exc:" logger.warn("error while processing item: %s", exc) Start importing the root logger in your module, then, using it in a few different places, you may eventually figure out a more sensible logging hierarchy. Tip 2: Use the logging module to report what happened in a way that is configurable independently from how you compose the module with other modules in a larger applications. You don't have to protect every single line or every single function call, but only the places where it makes a difference to survive the error. In your case it may be in the inside the loop. ![]() ![]() Tip 1: Trap the error at every level where it makes sense to continue processing. The following are a few basic strategies I regularly use in my more-than-trivial scripts and medium-size applications. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |