Try-except for flow control in reading Sqlite

Steven D'Aprano steve at pearwood.info
Mon Oct 28 02:18:09 EDT 2013


On Sun, 27 Oct 2013 20:43:07 -0700, Victor Hooi wrote:

> Hi,
> 
> I'd like to double-check something regarding using try-except for
> controlling flow.
> 
> I have a script that needs to lookup things in a SQLite database.
> 
> If the SQLite database file doesn't exist, I'd like to create an empty
> database, and then setup the schema.
> 
> Is it acceptable to use try-except in order to achieve this? E.g.:
> 
>     try:
>         # Try to open up the SQLite file, and lookup the required
>         entries
>     except OSError:
>         # Open an empty SQLite file, and create the schema

Yes, that's the right way to do it.


> My thinking is that it is (easier to ask forgiveness than permission),
> but I just wanted to check if there is a better way of achieving this?
> 
> I'd also be doing the same thing for checking if a file is gzipped or
> not - we try to open it as a gzip, then as an ordinary text file, and if
> that also fails, raise a parsing error.

Correct.

The problem with checking in advance is that there is a race condition 
between checking and the using the file:


if database exists: # at this moment, the file is guaranteed to exist
    # but a moment later, guarantee is no longer valid
    open database


In a multitasking operating system, some other process may have deleted 
the database. Or changed its name, removed your access privileges, even 
replaced it with a different file. Apart from hard-to-diagnose bugs, this 
is also the source of some security vulnerabilities:

https://www.owasp.org/index.php/Race_Conditions

Scroll down and read the section on "Time of check, time of use race 
condition".

So using a try...except block is precisely the right solution.



-- 
Steven



More information about the Python-list mailing list