Correct use of try,except and raise?

Bart Kastermans kasterma at bart-kastermanss-macbook.local
Sun Jul 13 12:32:12 CEST 2008


Roy Smith <roy at panix.com> writes:

> 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.

And you do that by

except IndexError:
   raise TheErrorYouNowWantToRaise

And
except IndexError, e:

if you want access to the exception as well.



More information about the Python-list mailing list