Exceptions and sqlite3 - python

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?

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

Related

Catch any of the errors in psycopg2 without listing them explicitly

I have a try and except block where I would like to catch only the errors in the psycopg2.errors and not any other error.
The explicit way would be:
try:
# execute a query
cur = connection.cursor()
cur.execute(sql_query)
except psycopg2.errors.SyntaxError, psycopg2.errors.GroupingError as err:
# handle in case of error
The query will always be some SELECT statement. If the execution fails it should be handled. Any other exception not belonging to psycopg, e.g. like ZeroDivisionError, should not be caught from the except clause. However, I would like to avoid to list all errors after the except clause. In fact, if you list the psycopg errors, you get a quite extensive list:
from psycopg2 import errors
dir(errors)
I have searched quite extensively and am not sure if this question has been asked already.
You can you use the base class psycopg2.Error it catch all psycopg2 related errors
import psycopg2
try:
cur = connection.cursor()
cur.execute(sql_query)
except psycopg2.Error as err:
# handle in case of error
see official documentation
Meanwhile, I have implemented by catching a generic Exception and checking if the exception belongs to the list returned by dir(errors). The solution proposed by Yannick looks simpler, though.
The function that I use prints the error details and checks using the name of the exception err_type.__name__ whether it is in any of the psycopg errors:
from psycopg2 import errors
def is_psycopg2_exception(_err):
err_type, err_obj, traceback = sys.exc_info()
print ("\npsycopg2 ERROR:", _err, "on line number:", traceback.tb_lineno)
print ("psycopg2 traceback:", traceback, "-- type:", err_type)
return err_type.__name__ in dir(errors)
Then, I use this function in the try/except clause:
try:
# execute a query
cur = connection.cursor()
cur.execute(sql_query)
except Exception as err:
if is_psycopg2_exception(err):
# handle in case of psycopg error
else:
# other type of error
sys.exit(1) # quit
For my very specific case, where I need to check for other other exceptions as well, I can readapt Yannick solution as follows:
try:
# execute a query
cur = connection.cursor()
cur.execute(sql_query)
except psycopg2.OperationalError as err:
# handle some connection-related error
except psycopg2.Error as err:
# handle in case of other psycopg error
except Exception as err:
# any other error
sys.exit(1) # quit

Inherit Base Python Error Exception Object (syntax)

In Visual Basic, there is an inherited base object that is effective for error debugging purposes. Is there an equivalent for the "Err" object in Python?
Dim Msg As String
' If an error occurs, construct an error message.
On Error Resume Next ' Defer error handling.
Err.Clear
Err.Raise(6) ' Generate an "Overflow" error.
' Check for error, then show message.
If Err.Number <> 0 Then
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & ControlChars.CrLf & Err.Description
MsgBox(Msg, MsgBoxStyle.Information, "Error")
End If
For example:
def exec_sproc(sql,cnxn):
try:
cursor=cnxn.cursor()
cursor.execute(sql)
cnxn.commit()
cursor.close()
except(err):
print("error: {0}".format(err))
There is a suggestion to try
except Exception,e: print str(e)
I get an invalid syntax because 'e' is not defined or in the former example err shows as invalid syntax.
What is the base error object in Python? In most examples, user-defined custom errors are demonstrated rather than coding a return of the actual "Python" error. If I know what the error is, I prefer not to make it. Instead, show me what Python sees as the error. (anything other than invalid syntax would help)
I guess this is what you are looking for
def exec_sproc(sql,cnxn):
try:
cursor=cnxn.cursor()
cursor.execute(sql)
cnxn.commit()
cursor.close()
except Exception as err:
print("error: {0}".format(err))
for more on Python exceptions look here

Python/Django: how do I determine the class to specify in an "except" statement?

I am working with some Python/Django code that I inherited. In it there is a DB call surrounded by a try block, with an "except Exception ex" statement to catch all exceptions. I want to be more selective, and catch only the exception type that I anticipate. By examining the Exception object that is caught, I can tell that it's of type "DatabaseError".
The comments in my code below show the many things I have tried, based on Googling the question and searching here, along with the errors that Python gives me when I try them. Most frustrating is that I've found plenty of examples on the web of code the people say works, that looks just like what I'm trying. But the code samples I find generally don't include the "import" lines.
I suspect I need to import something more, but I can't figure out what.
import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
connection = connections['ims_db']
sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
cursor = connection.cursor()
try:
cursor.execute(sqlUpdateQuery)
# this gets the error "Undefined variable 'Database'"
## except Database.DatabaseError as dbe3:
# this gets the error "Undefined variable 'Oracle'"
## except Oracle.DatabaseError as dbe2:
# this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
## except cx_Oracle.DatabaseError as dbe:
# this gets the error "Undefined variable 'DatabaseError'"
## except DatabaseError as dbe:
# this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
## except cx_Oracle as dbe:
# this gets the error "Module cx_Oracle has no '_error' member"
## except cx_Oracle._Error as dbe:
except Exception as ex:
# This gets the error "Module cx_Oracle has no 'DatabaseError' member"
## if isinstance(ex, cx_Oracle.DatabaseError) :
# This gets the error "Undefined variable 'DatabaseError'"
## if isinstance(ex, DatabaseError) :
className = type(ex).__name__
# This logs "... class = DatabaseError ..."
log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
args = ex.args
arg0=args[0]
# arg0ClassName is "_Error"
arg0ClassName = type(arg0).__name__
code = arg0.code
# codeClassName is "int"
codeClassName = type(code).__name__
msg = "Exception, code = {0}".format(code)
log.debug(msg)
raise
The correct syntax is as follows:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
You can see that syntax in a few of the samples (like TypeHandlers.py) that you can find here: https://github.com/oracle/python-cx_Oracle/tree/master/samples.
Try running the samples and working with them to see if you can resolve your issue. If not, please create an issue containing a complete runnable sample here: https://github.com/oracle/python-cx_Oracle/issues.

How to get the MySQL type of error with PyMySQL?

I'm doing a Python application with MySQL and PyMySQL and I'd like to be able to know the number of the MySQL error when I get one so that I can do something different depending on it.
Is there a way to do that with a try-except statement or another way?
Any exception in Python has an args member that shows you how it was constructed. For example:
>>> e = Exception(1, 2, 3, 4)
>>> e.args
(1, 2, 3, 4)
For pymysql, they're always constructed with (errno, errorvalue). So:
try:
do_stuff()
except MySQLError as e:
print('Got error {!r}, errno is {}'.format(e, e.args[0]))
I'm not sure this is guaranteed by the documentation, but you can see how it works pretty easily from the source.
pymysql maps mysql errors to python errors according to the following table:
_map_error(ProgrammingError, ER.DB_CREATE_EXISTS, ER.SYNTAX_ERROR,
ER.PARSE_ERROR, ER.NO_SUCH_TABLE, ER.WRONG_DB_NAME,
ER.WRONG_TABLE_NAME, ER.FIELD_SPECIFIED_TWICE,
ER.INVALID_GROUP_FUNC_USE, ER.UNSUPPORTED_EXTENSION,
ER.TABLE_MUST_HAVE_COLUMNS, ER.CANT_DO_THIS_DURING_AN_TRANSACTION)
_map_error(DataError, ER.WARN_DATA_TRUNCATED, ER.WARN_NULL_TO_NOTNULL,
ER.WARN_DATA_OUT_OF_RANGE, ER.NO_DEFAULT, ER.PRIMARY_CANT_HAVE_NULL,
ER.DATA_TOO_LONG, ER.DATETIME_FUNCTION_OVERFLOW)
_map_error(IntegrityError, ER.DUP_ENTRY, ER.NO_REFERENCED_ROW,
ER.NO_REFERENCED_ROW_2, ER.ROW_IS_REFERENCED, ER.ROW_IS_REFERENCED_2,
ER.CANNOT_ADD_FOREIGN, ER.BAD_NULL_ERROR)
_map_error(NotSupportedError, ER.WARNING_NOT_COMPLETE_ROLLBACK,
ER.NOT_SUPPORTED_YET, ER.FEATURE_DISABLED, ER.UNKNOWN_STORAGE_ENGINE)
_map_error(OperationalError, ER.DBACCESS_DENIED_ERROR, ER.ACCESS_DENIED_ERROR,
ER.CON_COUNT_ERROR, ER.TABLEACCESS_DENIED_ERROR,
ER.COLUMNACCESS_DENIED_ERROR)
if you want to catch the errors then you will need to catch ProgrammingError, DataError, IntegrityError, NotSupportedError, and OperationalError, individually. You can see specifically which mysql error was caught by coercing the exception to a string using str.
try:
#interact with pymysql
except ProgrammingError as e:
print "Caught a Programming Error:",
print e
for name, ddl in TABLES.iteritems():
try:
print("Creating table {}: ".format(name))
db.execute(ddl)
except pymysql.InternalError as error:
code, message = error.args
print ">>>>>>>>>>>>>", code, message
That's a start but loads of other errors exist eg. OperationalError

Identify the exception to be used from the traceback

I want to catch an exception when user fails login due to wrong password .
So i make a function using imaplib .I enter a wrong password and get a traceback with error details.
Now my question is actually general.How do you identify the exception we have to mention in our "try and except" body from the error messages?
These is what I got->
>>> count("testarc31#gmail.com","Xbox#36")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
count("testarc31#gmail.com","Xbox#36")
File "E:\Arindam\py_progs\Mail Notifier\0.0.19\Mail.py", line 24, in count
obj.login(m,p)
File "C:\Python27\lib\imaplib.py", line 500, in login
raise self.error(dat[-1])
error: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
If i want to make a try and except,what will i mention in the exception part?
try:
login(mail,pass):
except ????:
something
Question :
1) What will be ???? here . Can it be deduced directly from the error report?
2) Is there a basic idea to identify what is the exception we have to use from each error we get ?
You want to use something like this:
try:
..code that might raise an exception...
except ExceptionType, e:
...do something...
In your case, that probably want this:
try:
login(mail,pass)
except imaplib.IMAP4.error, e:
print "Ouch -- an error from imaplib!"
To identify the type of an exception, you can look at its exception message. In this case it's just "error" -- unfortunately the module name is not included. You can get a better idea of exactly where it comes from by doing:
try:
login(mail,pass)
except Exception, e:
print type(e)

Categories