Exception as the primary error handling mechanism?
aahz at pythoncraft.com
Sat Jan 2 08:02:50 CET 2010
In article <4B3DCFAB.3030909 at v.loewis.de>,
Martin v. Loewis <martin at v.loewis.de> wrote:
>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).
But you *still* need to catch IOError: someone might delete the file
after the test. Figuring out how to deal with race conditions is one of
the main reasons Alex Martelli advocates EAFP over LBYL.
Of course, in the real world, you often end up wanting to do it both
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
Weinberg's Second Law: If builders built buildings the way programmers wrote
programs, then the first woodpecker that came along would destroy civilization.
More information about the Python-list