Capture JythonExecException in script?

I can’t seem to figure out how to capture a Jython Exception in a try…except.

I have tried this format and it works for capturing database exceptions.

import java.lang.Exception

try:
# something something something
except Exception, e:
# jython exception
except java.lang.Exception, e:
# java exception

I have never been able to capture a JythonExecException. Like a divide by zero, or an exception with Sepasoft API, or an invalid reference or datatype passed into a function.

Is it possible? I am using Ignition v8.0.13.

I’m on 7.9 but I would assume it would be the same for 8.0. I have a number of shared functions that I call from gateway timer events. To capture any errors they get I use something like:

import traceback
import sys

def test():
	x = 1/0
	return x

try:
	test()
except Exception, err:
	exc_type, exc_value, exc_tb = sys.exc_info()
	errtb = traceback.format_exception(exc_type, exc_value, exc_tb)
	errStr = str("This Script returned an error: "+str(err)+errtb[1] + errtb[2])
#	logger = system.util.getLogger("testScript")
#	logger.info(errStr)
	print errStr

I commented out the logger part of it and used print to show you want it returns in the logs. I’m not sure if this is exactly what your looking for but its what I use for capturing exceptions in functions.

1 Like

@bpreston thanks for your response, I figured out my issue.

I was doing this:

import java.lang.Exception
	
try:

    h = 1/0

except Exception, e:
	# handle jython exceptions
	# Log the error.
    msg = e.getCause().getMessage()  # <<--- this was causing another exception
            

except java.lang.Exception, e:
    # handle java exceptions
	# Log the error.
	msg = e.getCause().getMessage()

I ended up doing this and I was able to capture the exception:

import java.lang.Exception
try:

    h = 1/0

except Exception, e:
    # handle jython exceptions
	# Log the error.
	msg = str(e)

except java.lang.Exception, e:
	# handle java exceptions
	# Log the error.
    msg = e.getCause().getMessage()

It just dawned on me that the Jython exception object is different that the java exception object. I was referencing a method that did not exist. It helps when I carefully read the exception in the log, it was trying to tell me. I also did not provide that detail in my original post, my bad.

@bpreston I like how you generated the error string for the Jython exception, I plan to use that. Thanks again.

1 Like