When to use try and except?

Chris Rebert cvrebert+clp at gmail.com
Fri Aug 29 14:33:24 EDT 2008


On Fri, Aug 29, 2008 at 10:56 AM, cnb <circularfunc at yahoo.se> wrote:
> On Aug 29, 7:40 pm, Daniel <daniel.watr... at gmail.com> wrote:
>> On Aug 29, 11:23 am, cnb <circularf... at yahoo.se> wrote:
>>
>> > If I get zero division error it is obv a poor solution to do try and
>> > except since it can be solved with an if-clause.
>>
>> > However if a program runs out of memory I should just let it crash
>> > right? Because if not then I'd have to write exceptions everywhere to
>> > prevent that right?
>>
>> > So when would I actually use try-except?
>>
>> > If there can be several exceptions and I just want to catch 1 or 2?
>> > Like
>> > try:
>> >     blahaba
>> > except SomeError:
>> >     do something
>>
>> I'm not sure whay you're trying to do, but I think catching a
>> ZeroDivisionError exception is a good use of try-except.
>>
>> I'm also not sure that I would say you just let a program crash if it
>> runs out of memory.  I would think that from the user perspective, you
>> would want to check memory conditions and come up with an exception
>> indicating that some memory threshold has been reached.  When that
>> exception is raised you should indicate that to the user and exit
>> gracefully.
>
>
> A ZeroDivisionError is better avoided wth an if-clause, don't you
> think? It is a predictable exception...

Basically, there's a general principle (EAFP: Easier to ask
forgiveness than permission) in Python to just "try" something and
then catch the exception if something goes wrong. This is in contrast
to e.g. C where you're supposed to "Look before you leap" (LBYL) and
check for possible error conditions before performing the operation.
One of the main advantages of the Python approach is that the
operation itself comes first in the code:

try:
    a = b/c
except ZeroDivisionError:
    #handle it

versus the LBYL approach:

if c == 0:
    #handle error
a = b/c

where if the error handling code isn't really short, it ends up
distracting you from the operation you're actually trying to perform.
This individual case (division by 0) might not be the best example due
to its simplicity, but you get the general point.

- Chris

> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list