R Exception Handling in Java

Once you have plugged the statistical software R (www.r-project.org) 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));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s