How to catch exceptions from database calls such as system.db.runPrepUpdate

I'm having trouble understanding how to comprehensively catch exceptions thrown while doing database updates. Here is an example where I tried to INSERT a string which could not be converted to a float into a column of type 'float', so obviously it threw an exception. Here is a part of it:

Caused by: org.python.core.PyException: java.lang.Exception: java.lang.Exception: Error executing system.db.runPrepUpdate(INSERT INTO TestTable (val) VALUES (?), [3z], XOM, , false, false)
	... 56 common frames omitted
Caused by: java.lang.Exception: Error executing system.db.runPrepUpdate(INSERT INTO TestTable (val) VALUES (?), [3z], XOM, , false, false)
	... 55 common frames omitted
Caused by: com.inductiveautomation.ignition.client.gateway_interface.GatewayException: SQL error for "INSERT INTO TestTable (val) VALUES (?)": Error converting data type nvarchar to float.

I'm especially interested in the last line since it tells me the real cause, as opposed to the java.lang.Exception, which doesn't tell me WHY the call failed. I wrap a lot of my code in exception catchers, and when I re-raise the exception the GatewayException is stripped out and I don't see it in the re-raised exception. Here's a simplified version of what I'm talking about:

import sys
anInt = '3z'
try:
	system.db.runPrepUpdate("INSERT INTO TestTable (val) VALUES (?)", [anInt], 'XOM')
except:
	errorType,value,trace = sys.exc_info()
	raise errorType, value, trace  # re-raise

which re-raises the java.lang.Exception part (so I see it in the console), but not the GatewayException part. What is the magic import and except clause which will allow me to catch the GatewayException?

See this topic:

1 Like

Also, note that java exceptions are allowed to have a "cause" attached, and that one can have a cause, et cetera. Look at e.cause.

1 Like

Thank you!

I knew the trick about catching Java exceptions separately from one of your other replies, but I didn't know about this until your "Generic Python error handler" response.

from java.lang import Throwable

Great advice! It turns out in my example case at the top of the thread, referencing the .cause property of the Java exception provides the exact cause I was looking for:

> print e.cause

com.inductiveautomation.ignition.client.gateway_interface.GatewayException: SQL error for "INSERT INTO TestTable (val) VALUES (?)": Error converting data type nvarchar to float.