When to use try and except?

George Sakkis george.sakkis at gmail.com
Fri Aug 29 13:42:11 EDT 2008


On Aug 29, 1:23 pm, 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?

Whenever you can do something *meaningful* in the except block to
handle the exception (e.g. recover). Is there any meaningful action
you can take when you run out of memory ? If yes (e.g. write current
data to the disk and open a popup window that informs ths user), then
use try/except, otherwise don't. IOW code like the following

    try:
        ...
    except MemoryError:
        print "You ran out of memory!"

is typically useless; better let the exception propagate to the top
level with a full traceback.

HTH,
George



More information about the Python-list mailing list