Correct use of try,except and raise?

ssecorp circularfunc at gmail.com
Sun Jul 13 03:10:58 CEST 2008


On Jul 13, 2:32 am, Roy Smith <r... at panix.com> wrote:
> In article
> <3b78898b-6131-4137-9c1d-64deaf460... at p25g2000hsf.googlegroups.com>,
>
>
>
>  ssecorp <circularf... at gmail.com> wrote:
> > 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)
>
> >     def push(self, item):
> >         self.stack.append(item)
>
> >     def pop(self):
> >         try:
> >             return self.stack.pop()
> >         except:
> >             raise IndexError, "pop from empty stack"
>
> > class Queue(object):
> >     def __init__(self, *items):
> >         self.queue = list(items)
>
> >     def append(self, item):
> >         self.queue.append(item)
>
> >     def pop(self):
> >         try:
> >             return self.queue.pop(0)
> >         except:
> >             raise IndexError, "pop from empty queue"
>
> I think you would do better defining a new exception, PopError, or
> something like that.  Then you can write code which specifically catches
> that and do something with it.
>
> It's also not a good idea to catch all exceptions.  Catch the most specific
> thing you can.  Consider something like:
>
> try:
>     kew.pop(0)
> except:
>    raise IndexError, "pop from empty kew"
>
> When I run it, it prints, "IndexError: pop from empty kew".  The problem
> is, the *real* error is "NameError: name 'kew' is not defined".  By
> catching all exceptions, I've masked a programming error by turning the
> NameError into an IndexError.



i dont get what you mean, if i dont do anything python will raise an
indexerror so it is an indexerror.



More information about the Python-list mailing list