Correct use of try,except and raise?
Ben Finney
bignose+hates-spam at benfinney.id.au
Sat Jul 12 22:32:06 EDT 2008
ssecorp <circularfunc at gmail.com> writes:
> Is this correct use of exceptions? to raise an indexerror and add my
> own string insetad of just letting it raise a IndexError by itself
> and "blaming" it on list.pop?
>
> class Stack(object):
> def __init__(self, *items):
> self.stack = list(items)
If you are passing a sequence conceptually, then it's more Pythonic to
pass it as a sequence explicitly::
def __init__(self, items):
""" Call with e.g. Stack(["foo", "bar"]) """
self.stack = list(items)
> def pop(self):
> try:
> return self.stack.pop()
> except:
> raise IndexError, "pop from empty stack"
Don't use this form of 'raise', it's deprecated. Instead, create the
exception instance with the arguments::
raise IndexError("pop from empty stack")
Don't use a bare 'except'; you will thereby catch *all* exceptions in
the 'try' block, masking errors you did not expect to handle, making
debugging unnecessarily difficult. Instead, always be explicit about
*which* exceptions you're handling here.
Don't catch the exception only to raise a new one; the context of the
original exception is lost. If all you want to do is have a different
message, modify the existing exception instance's args and re-raise
it.
try:
return self.stack.pop()
except IndexError, exc:
exc.args = ["pop from empty stack"]
raise
--
\ “Experience is that marvelous thing that enables you to |
`\ recognize a mistake when you make it again.” —Franklin P. Jones |
_o__) |
Ben Finney
More information about the Python-list
mailing list