Ignore exceptions

Jonathan Gardner jgardner at jonathangardner.net
Thu Jan 24 16:30:37 EST 2008


On Jan 24, 12:13 pm, SMALLp <po... at mzm.hr> wrote:
> Hy. Is there any way to make interrupter ignore exceptions. I'm  working
> on bigger project and i used to put try catch blocks after writing and
> testing code what's boring and it's easy to make mistake. I remember of
> something like that in C++ but I cant find anythin like that for python.
>

Hello. Two points with exceptions.

* Only write try blocks when you are actually going to do something
interesting with the exception. Otherwise, let the exception bubble
up.

* If you have unwanted exceptions, fix the root cause of the exception
rather than try to hide the exception. The exception is saying
something is wrong and needs attention. Provide that attention.

I have seen too many people write code in Java that simply masks all
exceptions because they don't want to write the interface to their
functions that describes what exceptions are possible. I have seen
comments around this code saying, "This should always work." Of
course, it doesn't always work and when it doesn't work, they don't
know about it and they don't even know how to tell what went wrong.

The emotion driving this exception masking practice I see in the Java
world is laziness, not correctness. This is not the good form of
laziness (where you want to write good code so you end up doing less
work) but the bad form (where you don't want to work at all).

There is no need to mask exceptions in Python. In fact, it is more
work to mask exceptions, and you should feel bad about all the extra
typing you are doing.

Once again: All try blocks should do something interesting when they
catch an exception. No exception should be ignored or thrown away.

A few sample good uses of try/except blocks:

(1) Do something else if an expected exception occurs.

  try:
    # There is a good chance an exception will be thrown. If so, I
want to do something else.
    d['foo'] += 5
  except KeyError:
    d['foo'] = 5

(2) Show a friendly error message when an exception occurs over a
significant chunk of the program. (Useful for websites and GUI apps.)

  try:
    # There is a very complicated piece of code. Any of a million
exceptions could occur.
    ...
  except:
    # Show a nicely formatted error message with hints on how to debug
the error.
    ...

Here are some bad examples:

(BAD)

   try:
     # I don't know what is happening in here, but it always throws an
exception.
     # I don't want to think about it because it makes my brain hurt.
     ...
   except:
     pass

(WORSE) The alternate form--try N times, masking the error each time--
is equally bad.

  while True:
    try:
      # Something could go wrong. What could go wrong? Who cares?
      ...
      break
    except:
      # We'll just keep trying forever....
      pass



More information about the Python-list mailing list