Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions and sqlite3

import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
try:
    cursor.execute("INSERT INTO loctions VALUES('Hogwarts', 'Scotland'")
    cursor.execute("INSERT INTO characters VALUES('Albus', 'Dumbledore')")
    conn.commit()

except sqlite3.OperationalError:
    print "Oops! This was an operational error. Try again..."

except sqlite3.NameError:
    print "Name Error"

except sqlite3.ValueError:
    print "value error"

except sqlite3.IOError:
    print "IO error"

conn.close()

I'm trying to figure out if the above is valid code. That is, can I have multiple exceptions after my "try" clause?

When I ran this by typing 'python filename.py', I saw "Oops! This was an operational error. Try again..." printed in my terminal.

This made sense because I had spelled the name of the first table wrong (loctions instead of locations), so it was an Operational Error.

But I'm confused about how to force a Name Error or a Value Error.

Also, when I commented out the "except sqllite3.OperationalError" clause, I got this error in my terminal:

Traceback (most recent call last):
  File "sqle.py", line 14, in <module>
    except sqlite3.NameError:
AttributeError: 'module' object has no attribute 'NameError'

Is this saying that there's no such thing as sqlite3.NameError? Yet sqlite3.OperationalError is a thing.

How do I discover what types of errors there are?

like image 842
LNA Avatar asked Apr 15 '26 20:04

LNA


1 Answers

NameError, ValueError, IOError are builtin exceptions. Don't qualify them with sqlite3.:

...
except NameError:
    print "Name Error"
except ValueError:
    print "value error"
except IOError:
    print "IO error"

To see which exceptions are defined in the module (using the property that exceptions are subclass of the Exception class):

>>> import inspect
>>> [name for name, value in vars(sqlite3).items()
     if inspect.isclass(value) and issubclass(value, Exception)]
['Warning', 'InternalError', 'ProgrammingError', ..., 'OperationalError']

Or consult the module documentation

like image 196
falsetru Avatar answered Apr 18 '26 08:04

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!