% Demonstrate
%    - how to handle exceptions in Java calls due to incorrect parameters;
%    - how to pass variables used in the Java call to the exception handler
%      and compensate for the exception by instantiating the variables
%      and continuing the workflow.

:- eval(ex017()).

ex017() :-
	SB = StringBuffer("To be compensated for"),
	% Define a handler for Java invocation exceptions:
	%    note that 'S' is a free variable here
	on_exception(ws.prova.calc.CalcException,on_calc_errors(S)),
	% This call has an extra parameter contradicting the signature.
	% If there were no exception handler, the code below would have failed.
	S = SB.toString(5),
	% This is reachable only because of the compensation in on_calc_errors().
	% Variable 'S' s now instantiated with a value set in on_calc_errors().
	println(["Compensated: ",S]).

on_calc_errors(S) :-
	exception(Ex),
	Cause = Ex.getCause(),
	S = "compensation",
	println([Cause]).
