% For Prova 1.7.1 or later.
% Examples of working with exceptions in Java calls and built-in predicates.
% Demonstrate
% - the propagation of handlers to embedded calls;
% - how to clear of exceptions;
% - how specifying handlers in embedded calls does not affect
%      higher level exceptions.

:- eval(ex010()).

filename("nosuchfile.txt").
filename("ex010.prova").

ex010() :-
	println(["-------------------"]),
	filename(Filename),
	% An exception handler for java.io.IOException and subclasses
	on_exception(java.io.IOException,catch_io_exception(Filename)),
	fopen(Filename,Reader),
	println(["File opened: ",Filename]).
ex010() :-
	println(["-------------------"]),
	filename(Filename),
	% An exception handler for java.io.IOException and subclasses
	on_exception(java.io.IOException,catch_io_exception(Filename)),
	% Unregister the handler
	on_exception(java.io.IOException,clear),
	% ...and register a more general one
	on_exception(java.lang.Exception,catch_io_exception(Filename)),
	% The handler works also for the exception in the following call 
	ex010_inner_a(Filename),
	println(["File opened: ",Filename]).
ex010() :-
	println(["-------------------"]),
	filename(Filename),
	% Here we define the handler in the inner call, so it will not work
	%    for the fopen that follows it.
	ex010_inner_b(Filename),
	fopen(Filename,Reader),
	println(["File opened: ",Filename]).

ex010_inner_a(Filename) :-
	% Because exception handlers are inherited from the calling clause
	%    even with no exception handlers specified here,
   %    the handler works for the following fopen.
	fopen(Filename,Reader).

ex010_inner_b(Filename) :-
	% An exception handler for java.io.IOException and subclasses
	on_exception(java.io.IOException,catch_io_exception(Filename)).

catch_io_exception(Data) :-
	println(["IO error occurred for ",Data]),
	exception(Ex),
	println([Ex]),
	fail().
