Re: Newbie: use of built-in exceptions

2013-09-02 Thread Rui Maciel
Chris “Kwpolska” Warrick wrote:

 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.

Ok, thanks for the tip.


Rui Maciel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: use of built-in exceptions

2013-09-02 Thread Cameron Simpson
On 01Sep2013 13:26, Chris “Kwpolska” Warrick kwpol...@gmail.com wrote:
| On Sun, Sep 1, 2013 at 1:17 PM, Rui Maciel rui.mac...@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 c...@zip.com.au

Whether you're getting laid or not, the glass is still half empty.
- Dan Hillman, alt.peeves Massgasm
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie: use of built-in exceptions

2013-09-01 Thread Rui Maciel
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?  


Thanks in advance,
Rui Maciel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: use of built-in exceptions

2013-09-01 Thread Chris “Kwpolska” Warrick
On Sun, Sep 1, 2013 at 1:17 PM, Rui Maciel rui.mac...@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.

-- 
Chris “Kwpolska” Warrick http://kwpolska.tk
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
-- 
http://mail.python.org/mailman/listinfo/python-list