Newbie: use of built-in exceptions

Cameron Simpson cs at zip.com.au
Mon Sep 2 20:36:42 EDT 2013


On 01Sep2013 13:26, Chris “Kwpolska” Warrick <kwpolska at gmail.com> wrote:
| On Sun, Sep 1, 2013 at 1:17 PM, Rui Maciel <rui.maciel at gmail.com> wrote:
| > Are there any guidelines on the use (and abuse) of Python's built-in exceptions, telling where
| > it's ok to raise them and where it's preferable to define custom exceptions instead?
| 
| There are no rules.  You should use common sense instead: if the
| exception fits your needs (eg. ValueError when incorrect output
| occurs) then use it.

A converse rule I use is: do I need to catch this specially and commonly?

My usual example is parsing: one could legitimately raise ValueError
for bad syntax, but I'd rather raise ValueError only for mistaken
calls to functions with bad values, so:

  class ParseError(ValueError):
    def __init__(self, context, complaint):
      self.context = context    # eg: file, lineno
      ValueError.__init__(self, complaint)

  def parse(filename):
    with open(filename) as fp:
      ... raise ParseError( (filename, lineno), "comma expected" )

  try:
    result = parse("datafile")
  except ParseError as e:
    ...

This also shows any reason: adding extra context information to an expection.

This is all just examples of course.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

Whether you're getting laid or not, the glass is still half empty.
        - Dan Hillman, alt.peeves Massgasm



More information about the Python-list mailing list