When to use try and except?

Carl Banks pavlovevidence at gmail.com
Sat Aug 30 00:24:28 EDT 2008


On Aug 29, 2:33 pm, "Chris Rebert" <cvrebert+... at gmail.com> wrote:
> On Fri, Aug 29, 2008 at 10:56 AM, cnb <circularf... 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.

I wouldn't say that the possibility of EAFP in Python makes it
obsolute to use LBYL.  (Error checking seems to be too broad a subject
to apply the One Obvious Way maxim to.)  C isn't always LBYL anyway;
sometimes it's DFTCFE "Don't forget to check for errors".

I tend to use EAFP to check if something "wrong" happened (a missing
file, invalid input, etc.), and LBYL for expected conditions that can
occur with valid input, even when that condition could be tested with
a try...except.  For instance, I'd write something like this:

if x is not None:
    y = x.calculate_value()
else:
    y = default_value

Main reason I do this is to document that None is an expected and
valid value for x, and not incidative of a problem.  But it's purely a
matter of style and neither way is wrong.


Carl Banks



More information about the Python-list mailing list