Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #53542 > unrolled thread
| Started by | Cameron Simpson <cs@zip.com.au> |
|---|---|
| First post | 2013-09-03 10:36 +1000 |
| Last post | 2013-09-03 10:36 +1000 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Newbie: use of built-in exceptions Cameron Simpson <cs@zip.com.au> - 2013-09-03 10:36 +1000
| From | Cameron Simpson <cs@zip.com.au> |
|---|---|
| Date | 2013-09-03 10:36 +1000 |
| Subject | Re: Newbie: use of built-in exceptions |
| Message-ID | <mailman.525.1378168617.19984.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web