开发者

Raise an error in SWI Prolog

I'd like to print a message and stop the evaluation of the predicate. How do I do开发者_StackOverflow社区 that?


Take a look at this link where the catch/3 and throw/1 mechanisms in Prolog are described.

It is possible to throw an exception or handle an exception using this mechanism.

The example (given on the site) is:

  p:- true.
  p:- throw(b).
  q:- catch(p, B, write('hellop')), r(c).
  r(X) :- throw(X).

Then the call:

 ?- catch(p, X, (write('error from p'), nl)).

will illustrate the ecxeption handling.


I played with a few other examples which I found. This might be usefull.

p :- throw(b).
r(X) :- throw(X).
q:- catch(p, B, format('Output1: Error from throwing p')), r(B). 

catch(throw(exit(1)), exit(X), format('Output: `w', [X])).
Output: 1
1 is thrown to catcher 'exit(X)' and recovered by format('Output: ~w', [X])),

catch(p, C, format('hellop')).   
Output: hellop 
p throws 'b' which is recovered by writing 'hellop' 

catch(q, C, format('Output2, Recovering q: helloq ')).
Output1: Error from throwing p
Output2, Recovering q: helloq

Ben


The stderr stream is aliased to user_error (see https://www.swi-prolog.org/pldoc/man?section=streamalias )

You can write a term (like a string) to a stream using write/2.

You can stop the program using halt.

For example:

% Happy case. Comes first, uses ! to avoid taking the alternative branch
foo(X) :- bar(X, Y), baz(Y), !.

% Fallback branch, in case the above failed. Writes a message and halts.
foo(X) :-
  write(user_error, "Couldn't foo"),
  halt.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜