Exception as the primary error handling mechanism?

Martin v. Loewis martin at v.loewis.de
Fri Jan 1 11:34:19 CET 2010


Peng Yu wrote:
> I observe that python library primarily use exception for error
> handling rather than use error code.
[...]
> It says "Another popular design flaw—namely, throwing exceptions for
> expected outcomes—also causes inefficiencies because catching and
> handling exceptions is almost always slower than testing a return
> value."
> 
> My observation is contradicted to the above statement by Henning. If
> my observation is wrong, please just ignore my question below.

Your observation is not wrong, but, as Benjamin already explained,
you are misinterpreting Michi Henning's statement. He doesn't condemn
exception handling per se, but only for the handling of *expected*
outcomes. He would consider using exceptions fine for *exceptional*
output, and that is exactly the way they are used in the Python API.

Notice that in cases where the failure may be expected, Python
also offers variants that avoid the exception:
- if you look into a dictionary, expecting that a key may not
  be there, a regular access, d[k], may give a KeyError. However,
  alternatively, you can use d.get(k, default) which raises no
  exception, and you can test "k in d" in advance.
- if you open a file, not knowing whether it will be there,
  you get an IOError. However, you can use os.path.exists in
  advance to determine whether the file is present (and create
  it if it's not).

So, in these cases, it is a choice of the user to determine whether
the error case is exceptional or not.

Regards,
Martin



More information about the Python-list mailing list