Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise an error in SWI Prolog

Tags:

prolog

I'd like to print a message and stop the evaluation of the predicate. How do I do that?

like image 963
Koen Avatar asked Mar 31 '11 12:03

Koen


People also ask

Does Prolog have exception handling?

Exception handling in prolog is done with the catch function. We use it below to make sure we can open the requested file. The first parameter of catch is the Goal, or what we want to execute (comparable to a try in C or Java). The second parameter is what exception we want to catch.

What is S () in Prolog?

They are just terms, a representation of the successor of their argument. So, s(0) is used to represent the successor of 0 (i.e. 1 ), s(s(0)) is used to represent the successor of s(0) (i.e. 2 ), and so on and so forth.

What does false mean in Prolog?

The concept of logical negation in Prolog is problematical, in the sense that the only method that Prolog can use to tell if a proposition is false is to try to prove it (from the facts and rules that it has been told about), and then if this attempt fails, it concludes that the proposition is false.

Which command is used to exit from SWI-Prolog?

If you want to exit SWI-Prolog, issue the command halt., or simply type CTRL-d at the SWI-Prolog prompt.


2 Answers

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.

like image 133
Vincent Ramdhanie Avatar answered Oct 02 '22 22:10

Vincent Ramdhanie


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

like image 21
Ben Engbers Avatar answered Oct 02 '22 22:10

Ben Engbers