Call-in Exception Handling

This example deals with Prolog predicates that throw an exception. We want to call a predicate that will throw a custom ball which we will then analyse. The predicate will be defined in a Prolog text. It is stored in the file ‘inthrow.p’ of folder ‘example02’:

throw_ball :- throw(ball(123)).

Let’s assume that the Java application already consulted this file. We want the Java application to catch the exception that is thrown by the predicate. For this purpose we simply wrap the predicate call into a Java try-catch statement:

  try {
Object throwGoal = "throw_ball";
inter.iterator(throwGoal).next().close();
} catch (InterpreterException capturedException) {

The Java application can now analyse the captured object. As a first step we recover the exception term that was thrown. This is done via the method getValue():

  Object exceptionTerm = capturedException.getValue();

In the analysis itself we check for the type, arity and functor of the exception term. This is readily done by a Java type check and then via accessing the getArity() and getFunctor() methods of the TermCompound:

  if (exceptionTerm instanceof TermCompound &&
((TermCompound) exceptionTerm).getArity() == 1 &&
((TermCompound) exceptionTerm).getFunctor().equals("ball")) {

When we have hit the correct compound we can write out its argument. This time we access the getArg() method from the TermCompound. Note that the argument numbering starts with zero (0) and not with one (1) as in the predicate arg/3:

       Writer wr = (Writer) 
inter.getProperty(ToolkitLibrary.PROP_SYS_CUR_OUTPUT);
wr.write(inter.unparseTerm(0,
((TermCompound) exceptionTerm).getArgWrapped(0)));
wr.write('\n');
wr.flush();

When we did not hit on the exception we simply do nothing. The example is found in the Java class InThrow. We can now run the example similar as we have done in the first example by an appropriate command line. The following line will be displayed on the standard output as a result:

123

Kommentare