Modern recommended exception handling practices?

Steven D'Aprano steve at pearwood.info
Tue Nov 3 02:22:30 EST 2015


On Tue, 3 Nov 2015 06:16 pm, Chris Angelico wrote:

> Not to mention having race condition possibilities.

Arrggghhh! I knew there was something else I wanted to say.

You're right. Sometimes you *have* to use exception handling code. Take this
for example:


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

That might be good enough for a quick and dirty script, but it's wrong,
because there's a race condition between the time you check whether the
file exists and the time you actually try to open it. (There are other
problems too: just because the file exists doesn't mean you have read
permission to it.) A lot can happen in the few microseconds between
checking for the existence of the file and actually opening it -- the file
could be renamed or deleted.

https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use


-- 
Steven




More information about the Python-list mailing list