tags:

views:

20

answers:

1

Given:

fruitid('Apple', 'Granny Smith', 1).
fruitid('Pear', 'Bartlett', 2).

If I had the clause

type_of_fruit(ID):-
       fruitid(Fruit, _, ID), write(Fruit).

How could I implement a method to catch erroneous inputs?

For instance

fruitid(5).

Thanks.

AS

A: 

Set Prolog Flags and Use Catch/3

Assuming SWI Prolog

1) The prolog_flags can change error behavior. First allow the system to catch the error and report it. The unknown flag is for unknown predicates such as fruitID/1.

set_prolog_flag(report_error,true).
set_prolog_flag(unknown,error). 

Now when the wrong predicate arity is used, there should be an error message like this:

?- fruitid(5).
ERROR: toplevel: Undefined procedure: fruitid/1 (DWIM could not correct goal)

2) To trap exceptions such as this in code, Wrap the goal in a catch/3 predicate. The settigs from 1) are stil required. This is the way to trap undefined predicate in code, or to trap any exception for that matter. Replace format/3 with the desired handler:

while_running_some_program:-
    catch(foodid(5), 
        error(Err,_Context),
        format('You done goofed! ~w\n', [Err])),
    rest_of_code.
Frayser