3

I use these code in my jython script

 try: my_func() except Exception as e: print e pass 

But I still get exception such as

java.io.FileNotFoundException: java.io.FileNotFoundException: ./filename (No such file or directory) 

or

java.io.EOFException: java.io.EOFException 

How can I catch all these java exceptions in jython?

Env info:

jython version 2.7.1

java runtime 10.0.2

1 Answer 1

2

Java exceptions in Jython are not derived from Python's Exception class. To catch them separately from Python exceptions import java.lang.Exception with some local name not overlapping with standard Exception and add another except clause:

from java.lang import Exception as JException try: my_func() except Exception as e: print "python ex", e except JException as ex: print "java ex", ex 
Sign up to request clarification or add additional context in comments.

4 Comments

Please explain why this solution work, answers with only code may be deleted.
this only works with python 2 because of the old print syntax, and old exception syntax. Consider upgrading to new syntax (which also works with python 2.7). OP has used except Exception as e. There's potential in your answer, but add some explanation and make it python 3 compliant.
@jcubic okay, added an explanation.
@Jean-François Fabre as you may know the latest Jython version is 2.7.1; considering the project activity Jython 3.5 will never be released.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.