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
Related
I'm putting errors in Try and Except, but I'm having trouble with 2 types of errors. I'll give you an example of what I need. This except with Valure Error works fine, because I know the error is called ValueError, so:
#ONLY EXAMPLE
except ValueError:
return "FAILED"
EXCEPT ERROR N.1
The question I ask you is: how should I write for the following error? It consists of the wrong name of an html class when scraping. I wrote selenium.common.exceptions.NoSuchElementException, but the error search does not work (the script does not open at all)
except selenium.common.exceptions.NoSuchElementException:
return "FAILED"
EXCEPT ERROR N.2
Same thing for the database insert error. I want to make sure that if 0 records are saved in the database then I have an error. I tried to write like this, but it's not good:
except records_added_Results = records_added_Results = + 0:
return "FAILED"
I wrote this because I have this code for the insertion in the database. It works correctly, I am writing it just to make you understand:
con = sqlite3.connect('/home/mypc/Scrivania/folder/Database.db')
cursor = con.cursor()
records_added_Results = 0
Values = ((SerieA_text,), (SerieB_text,)
sqlite_insert_query = 'INSERT INTO ARCHIVIO_Campionati (Nome_Campionato) VALUES (?);'
count = cursor.executemany(sqlite_insert_query, Values)
con.commit()
print("Record inserted successfully ", cursor.rowcount)
records_added_Results = records_added_Results + 1
cursor.close()
How should I write? Thank you
Import the exception before you try to catch it. Add this line to your imports:
from selenium.common.exceptions import NoSuchElementException
Then you can simply do:
try:
#code that could raise the NoSuchElementException
except NoSuchElementException:
#exception handling
For the other exception, it looks like you're trying to raise an exception. Consider something like this:
if records_added_Results == 0:
raise ValueError("error message")
Code:
def ScanNetwork():
nmScan = nmap.PortScanner()
s = nmScan.scan("192.168.1.1/24", '0-4444', arguments="-O")
for host in nmScan.all_hosts():
if nmScan[host].state() == "up":
print("Host : %s (%s)" % (host, nmScan[host].hostname()))
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
for proto in nmScan[host].all_protocols():
print("---------------------------")
print("\nProtocol : %s" % proto)
lport = nmScan[host][proto].keys()
lport = sorted(lport)
for port in lport:
print("\nport: " + f'{port}' + "\tstate: " + nmScan[host][proto][port]['state'])
print("---------------------------\n")
print("\n\nScan Completed!")
ScanNetwork()
Sometimes an exception occurs when the nmap fails to identify the Version or the Os running in a host. (It's a KeyError exception)
The part which is supposed to handle that exception is this:
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
I of course assume that there's nothing wrong with nmap's output and I've again made a huge beginner mistake and that's the reason my code is getting stuck..
Notes:
I've left the script running over night incase it returned some useful info but nothing happened!
Please do not tell me that I need to quit using the nmap module and turn to nmap3
Having tired you with all the above, does anyone know a way to still handle that exception without the code getting stuck?
You have forgotten to add the type of the exception to excpect while running the code inside the try-except block.
This should fix it:
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\n" + "Type: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except KeyError:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
In case you want to catch any possible exception that could occur (and yes custom ones included) then you should use the following code:
try:
<some critical code with possible exceptions to catch>
except Exception:
print("An exception occured")
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.
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
I got this code..
.....
try:
task_db.cursor.execute('DROP TABLE IF EXISTS `tasks`')
print "Affected: %d" % task_db.cursor.rowcount
except MySQLdb.Error, e:
print "Error ocurred: %s " % e.args[0]
print e
If the tasks table doesn't exist, then I get a warning like
create_database.py:11: Warning: Unknown table 'tasks'
But if the table does exist then I wont get that warning.
Odd?
Catching the MySQLdb.Warning didn't work for me, so I found another way to suppress warnings:
import warnings
warnings.filterwarnings("ignore", "Unknown table.*")
And you can edit the second parameter with whatever you want to suppress.
The most elegant way to avoid Mysql warnings :
from warnings import filterwarnings
import MySQLdb
filterwarnings('ignore', category = MySQLdb.Warning)
It's perfectly correct behaviour. If the table exists, then it's dropped. If it doesn't exist then you get Warning exception which is not the same as Error - you are free to ignore it and nothing bad should happen, but you have to catch it to allow your script to proceed.
EDIT:
To prevent Warning from bubbling up, just catch it as any other exception:
try:
[some code]
except MySQLdb.Warning:
[exception handling code]