Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python try, except an error from modules that where not imported explicitly

When a module class is not in my script but used by one of the modules (I did imported explicitly) how do I catch his error?

For example:

from sqlite3 import dbapi2 as sqlite

class sqldb:

def __init__(self):
  self.sqlite.connect('records.db')
  self.c = self.conn.cursor()    

def query(self,query,values)
 try:
  self.c.execute(query, values)
  self.conn.commit()
 except sqlite3.OperationalError:
  print "SQLite DB locked"

Will result in (when the database is locked):

NameError: global name 'sqlite3' is not defined

But when I don't catch the error it gives me exactly that exception: 'sqlite3.OperationalError'

So what should I put as Except ? Or should I just import the whole sqlite3 module? If yes, doesn't this increase the resources footprint of my program?

like image 434
Sebastian Avatar asked Feb 14 '12 12:02

Sebastian


1 Answers

Put the following line at the top of your program:

import sqlite3

to tell Python to associate the name sqlite3 with the module.

Alternatively, you can explicitly import the error you are catching:

from sqlite3 import OperationalError

...

try:
    self.c.execute(query, values)
    self.conn.commit()
except OperationalError:
    print "SQLite DB locked"
like image 134
sverre Avatar answered Oct 03 '22 23:10

sverre