Innovation through insight. Thinking lean and moving agile when delivering software products. Big Data, UX, Apache Wicket, JEE, Spring, MongoDB, Hadoop, R. Comsysto is a DZone MVB and is not an employee of DZone and has posted 44 posts at DZone. You can read more from them at their website. View Full User Profile

R Exception Handling in Java

  • submit to reddit

Once you have plugged the statistical software R ( in to your Java application (see blog entry about how to setup a connection from Java to R) you probably want to make sure that R does what you plugged it in for – not more and not less.

Our use case is to call an R script from the Java application in order to analyse application data. In particular, the Java application writes data to a csv file that is read into R where it is analysed and visualised. The visualisations are saved into pdf files which are the desired R script output. However, as soon as anything changed with the csv such that the R script bugged, the pdfs were not created, but the Java application kept on running without any notice.

A typical data scientist will agree that one usually writes an analytic R script in a way that it fits the one data set you have (basically without any error handling because you know the form of intermediate in- and output). If you have more than one data set you might write more generic analytic code, but anyway you don’t try to catch any possible exception simply because it’s impossible to write clear analytic R code while handling all possible exceptions.

For our use case we opted for a relatively simple R error handling strategy: The typical (rather non-error proof) analytic R script is called by another R script that wraps the source() command into the tryCatch.W.E() error function of R and saves the result into a list. The resulting list is then searched for errors.

scriptResult <- tryCatch.W.E( source(analysisScript) )
isError <- grep("error",tolower(is(scriptResult$value)))

In the Java application you only call the R wrapper script and its result. If the result indicates an error the Java application throws an exception or warning in order to indicate that the R script did not run as expected:

int isError = (int) rengine.eval("as.double(isError)").asDouble();
if (isError == 1) {
   String error = rengine.eval("paste(scriptResult$value)").getContent().toString();
   String msg = "script 'analysis.R': %s";
   LOGGER.error(String.format(msg, error));
Published at DZone with permission of Comsysto Gmbh, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)