Permalink
Browse files

Fix JepException cause on Python 3.x

  • Loading branch information...
bsteffensmeier committed Jul 12, 2017
1 parent 3b4a2e9 commit 5c88b4b33037f0187c5d484d5004e8849c37797b
Showing with 64 additions and 4 deletions.
  1. +18 −4 src/jep/jep_exceptions.c
  2. +40 −0 src/jep/test/TestExceptionCause.java
  3. +6 −0 tests/test_exceptions.py
View
@@ -91,15 +91,29 @@ int process_py_exception(JNIEnv *env)
/*
* If Python went through PyErr_NormalizeException(...), then
* it's possible a PyJObject pvalue was moved to
* pvalue.message.
* pvalue.message. PyErr_NormalizeException is called whenever
* there is an except: block even if the error is not actually
* caught.
*/
PyObject *tmp = PyObject_GetAttrString(pvalue, "message");
if (tmp != NULL && PyJObject_Check(tmp)) {
#if PY_MAJOR_VERSION < 3
PyObject *message = PyObject_GetAttrString(pvalue, "message");
if (message != NULL && PyJObject_Check(message)) {
Py_DECREF(pvalue);
pvalue = tmp;
pvalue = message;
}
#else
PyObject *args = PyObject_GetAttrString(pvalue, "args");
if (args != NULL && PyTuple_Check(args) && PyTuple_Size(args) > 0) {
PyObject *message = PyTuple_GetItem(args,0);
Py_INCREF(message);
Py_DECREF(pvalue);
Py_DECREF(args);
pvalue = message;
}
#endif
}
if (PyJObject_Check(pvalue)) {
// it's a Java exception that came from process_java_exception(...)
jstring jmessage;
@@ -0,0 +1,40 @@
package jep.test;
import java.lang.IndexOutOfBoundsException;
import jep.Jep;
import jep.JepConfig;
import jep.JepException;
/**
* Tests that a java excetion thrown while executing python is set as the cause
* of the JepException.
*
* Created: July 2017
*
* @author Ben Steffensmeier
*/
public class TestExceptionCause {
public static void main(String[] args) throws JepException {
JepConfig config = new JepConfig().addIncludePaths(".");
try (Jep jep = new Jep(config)){
jep.eval("from java.util import ArrayList");
try{
jep.eval("ArrayList().get(0)");
}catch(JepException e){
if (!(e.getCause() instanceof IndexOutOfBoundsException)) {
throw e;
}
}
try{
jep.eval("try:\n ArrayList().get(0)\nexcept AttributeError:\n pass");
}catch(JepException e){
if (!(e.getCause() instanceof IndexOutOfBoundsException)) {
throw e;
}
}
}
}
}
View
@@ -2,6 +2,8 @@
import unittest
import jep
from java.lang import Integer, String
import sys
from jep_pipe import jep_pipe, build_java_process_cmd
from java.io import FileInputStream
@@ -77,5 +79,9 @@ def test_arithmetic_error(self):
except ArithmeticError as ex:
pass
@unittest.skipIf(sys.platform.startswith("win"), "subprocess complications on Windows")
def test_exception_cause(self):
jep_pipe(build_java_process_cmd('jep.test.TestExceptionCause'))
# TODO come up with a way to test MemoryError and AssertionError given
# I coded support for that.

0 comments on commit 5c88b4b

Please sign in to comment.