Search code examples
javarrjava

rJava: How to get stack traces / more verbose error?


is there a way to have rJava print out the complete stack trace of an error, instead of just the exception? For example, this code (an attempt to call the Ambit2 cheminformatics library from R)

smrkMan <- .jnew("ambit2.smarts.SMIRKSManager", dcob)
reaction <- .jcall(smrkMan, "Lambit2/smarts/SMIRKSReaction;", "parse", ">>C" )
res <-  .jcall(smrkMan, "Z", "applyTransformation", AC, 
             .jnull("ambit2/smarts/IAcceptable"),
             reaction)

only gives me

Fehler in .jcall(smrkMan, "Z", "applyTransformation", AC,
.jnull("ambit2/smarts/IAcceptable"),  : 
java.lang.NullPointerException

which is not terribly useful, I would like to see which line it fails at so I can go back and trace it in the source...

Any possibility?


Solution

  • You can use .jgetEx() to get the exception object and print the stack trace:

    > .jcall("C",,"main",check=FALSE)
    > ex=.jgetEx()
    > .jcheck()
    Error: java.lang.Exception: foo
    > ex$printStackTrace()
    java.lang.Exception: foo
        at C.main(C.java:3)
    

    with

    public class C {
      static void main() throws Exception {
      throw new Exception("foo"); } }
    

    Just make sure you call .jclear() or .jcheck() before calling printStackTrace(), since Java won't do anything until you clear the exception.