Search code examples
pythonjython

How can I ignore all java.io exception?


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


Solution

  • 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