Try-except for flow control in reading Sqlite

Steven D'Aprano steve at pearwood.info
Mon Oct 28 03:19:31 EDT 2013


On Mon, 28 Oct 2013 18:01:49 +1100, Chris Angelico wrote:

> On Mon, Oct 28, 2013 at 5:57 PM, Victor Hooi <victorhooi at gmail.com>
> wrote:
>> Hi,
>>
>> We're on Python 2.6 (RHEL based system...) - I don't believe this
>> exposes FileNotFoundError =(.
> 
> Ah! I forgot about 2.x, sorry for the nose. Yep, catching OSError would
> be the thing to do, then!


I believe that in 2.x the error will be IOError, not OSError, at least 
for the built-in open() function.

But in either case, you should still check the errno, and if it isn't the 
error number you expect, re-raise.

try:
   ...
except OSError as e:
    if e.errno == 2:
        # recover from file not found
        ...
    else:
        # any other error
        raise


See the "errno" module for symbolic names for the various constants.

http://docs.python.org/2/library/errno.html



-- 
Steven



More information about the Python-list mailing list