Exception handling wart in Python

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Fri Nov 2 14:37:22 EST 2001


On Thu, 01 Nov 2001 19:35:46 -0500, Leo Lipelis <aeoo at myrealbox.com> wrote:
>Hi Pythoneers,
>
>I'd like some help with an issue I have with Python.  Simply put, I think
>having an exception mechanism is a waste if there is no tool that will let
>you know which unhandled exceptions exist at point foo.  I have spoken
>about this issue briefly with Neal, of the PyChecker fame, and he seemed to
>agree with me.
>
>I realize that it's a difficult problem to solve, but I think it would be
>worth solving at the language level, similarly to the way it's done in
>Java.  Let's say I call a function in some module,
>

I've used both Java and Python.  My thoughts on this:

- Java style exception is simply impossible in Python.  To know the
  exceptions pontentially raised by _something_ refered by a name, you have
  to know before hand what that _something_ is (types, attributes,
  arguments, etc).  But in Python these properties are associated with
  objects, not names.  For example, you can not determine the exceptions
  raised by

    a, b = c(d)

  until the names are bound to specific objects.  But if you can determine
  them in advance, you might just have solved the problem of static type
  checking in Python, which would be far more useful.

- Python style exception is actually more useful in practice than Java
  style.  Since you are not required to catch exceptions until you want to,
  you can let them propagate during development until you are ready to
  handle them properly.  The final code is very robust, and any exceptions
  left would be those that you haven't anticipated anyway.  If there is a
  special section of your code that can't tolerate any exceptions, you can
  just catch all of them at that point.  On the other hand, in Java you are
  forced to deal with all theoretically possible but practically very
  improbable exceptions early on during development.  To move the process
  forward some programmers catch all of them and ignore them, or handle them
  in a very superficial way.  This leaves some very subtle bugs in the final
  product where ignored exceptions go undetected.

Exception is a mechanism to treat low probability situations so that they do
not distract the main flow of the program.  Python allows you to ignore them
or handle them any way you like, so that you can concentrate on the main
thing you are doing.  Java forces you to treat them all explicitly, which
sort of defeats its purpose.  It becomes essentially a glorified
condition-goto structure.  Since in any real world situation the probability
distribution of cases are far from uniform, I find Python style exceptions
far more efficient.

Huaiyu



More information about the Python-list mailing list