When to use try and except?

Carl Banks pavlovevidence at gmail.com
Fri Aug 29 21:45:27 EDT 2008


On Aug 29, 1:56 pm, 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...

Many Pythonistas would disagree with that.

Anyway there are some types of errors for which catching exceptions is
more robust because there's a gap between the time something is
checked and the time it's used, between which the circumstances can
change.

For instance, the following test can be subject to sporadic failures:

if os.path.exists(filename):
    f = open(filename)

Between the call to os.path.exists and the call to open, the file
could be removed by another process, which will result in an unhandled
exception.  Also, sometimes files fail to open for other reasons, such
as permissions.

For things like divide-by-zero, there's no way a local value can
change between the zero test and the operation (except in uncommon
situations), so it's just a matter of style which way you do it.


Carl Banks



More information about the Python-list mailing list