Correct use of try,except and raise?

Roy Smith roy at panix.com
Sun Jul 13 02:32:53 CEST 2008


In article 
<3b78898b-6131-4137-9c1d-64deaf460ee6 at p25g2000hsf.googlegroups.com>,
 ssecorp <circularfunc 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.



More information about the Python-list mailing list