Correct use of try,except and raise?

Roy Smith roy at panix.com
Sat Jul 12 21:33:13 EDT 2008


ssecorp <circularfunc at gmail.com> wrote:

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

You wrote:

> > >     def pop(self):
> > >         try:
> > >             return self.queue.pop(0)
> > >         except:
> > >             raise IndexError, "pop from empty queue"

You are assuming that the only possible exception that can be thrown by 
"return self.queue.pop(0)" is IndexError.  Maybe, maybe not.  I gave you 
one example of how something else could be thrown -- a typo in your code 
leading to a NameError.  Maybe even something more exotic like MemoryError?

The defensive thing to do is catch exactly the exception you expect to 
happen.  In this case, that means IndexError.



More information about the Python-list mailing list