Initializing help system before first use

Handling exceptions thrown by a Java method called from a Mosel model


Description: Demonstrates how a Mosel model can handle exceptions thrown by Java methods. The Java class exports a method 'readFileToString' which takes a pathname and returns its content as a Java String. The Mosel model attempts to call this method, passing it the filename of a file that does not exist. Java will throw a FileNotFoundException; the Mosel model checks for the error and outputs a message to the output stream. You must compile the Java file before running the example - e.g. javac FileUtils.java
File(s): handleerror.mos, FileUtils.java

handleerror.mos
(!*******************************************************
   file handleerror.mos
   ````````````````````
   a model that demonstrates handling exceptions thrown by Java code

   (c) 2016 Fair Isaac Corporation
       author: J. Farmer, 2016
  *******************************************************!)


model myModel
  uses 'mosjvm','mmsystem'
  
  declarations
    classAndMethodName = "FileUtils.readFileToString"
    fileToRead = "input.txt"
    result: text
  end-declarations
 
  ! Tell Java to look for classes in work directory
  setparam('jvmclasspath',getparam('workdir'))
 
  ! Call into Java to read file
  ! (note that the given filename does not exist, so the Java class will throw a FileNotFoundException)
  result := jvmcalltext( classAndMethodName, fileToRead )
  if jvmstatus=false then
    writeln('ERROR from Java: ',jvmgetexceptionclass,': ',jvmgetexceptionmsg)
    exit(8)
  else
    writeln('Read data from ',fileToRead,' as follows:')
    writeln(result)
  end-if
end-model

FileUtils.java
/**
 * Example Java class, defining file-related utility functions
 *
 * @author  J.Farmer, (c) Fair Isaac Corporation, 2016
 **/

import java.io.*;

public class FileUtils {

	/**
	 * Given a file path, read the file content into a string
	 **/
	public static String readFileToString(String path) throws IOException {
		StringWriter result = new StringWriter();
		try (Reader in = new BufferedReader(new FileReader(path))) {
			int c;
			while ((c=in.read())!=-1) {
				result.write(c);
			}
		}
		return result.toString();
	}

}