Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #53542
| Date | 2013-09-03 10:36 +1000 |
|---|---|
| From | Cameron Simpson <cs@zip.com.au> |
| Subject | Re: Newbie: use of built-in exceptions |
| References | <CAMw+j7+wyiaDxrFthss1Edh+fe-Wqb4mTt8i8xZrXBKaUjjA0g@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.525.1378168617.19984.python-list@python.org> (permalink) |
On 01Sep2013 13:26, Chris “Kwpolska” Warrick <kwpolska@gmail.com> wrote:
| On Sun, Sep 1, 2013 at 1:17 PM, Rui Maciel <rui.maciel@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@zip.com.au>
Whether you're getting laid or not, the glass is still half empty.
- Dan Hillman, alt.peeves Massgasm
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Newbie: use of built-in exceptions Cameron Simpson <cs@zip.com.au> - 2013-09-03 10:36 +1000
csiph-web