2

when using this code this exception was raised and didn't return failure:

in Sicstus Polog:

Syntax error in number_codes/2 ! number syntax ! in line 0

in SWI-Prolog:

ERROR: number_chars/2: Syntax error: Illegal number

number_codes(Number,"m"),
catch(number_codes(Number,List),error(syntax_error(_),_), fail). 

how to make it return failure on this exception.

false
  • 10,264
  • 13
  • 101
  • 209
  • I've never used `catch` but according to the documentation here http://www.swi-prolog.org/pldoc/man?predicate=catch/3 it si a meta predicate like call and so you do not need to have number_codes called earlier – rano Nov 24 '13 at 09:15

2 Answers2

4

The ISO way to catch a syntax error is to write:

catch(number_codes(Number,"m"),error(syntax_error(_),_), fail).

The first argument is the goal to be protected, the second argument is the pattern to be caught. In this case, you want to catch an error. Errors are all of the form error(E,_) where the first argument is the concrete error term, in this case syntax_error(_). The second argument is implementation defined. So you cannot rely on its precise format.

Never simply catch everything (as @CapelliC) suggested. In this manner you might unintentionally hide some unexpected errors.

false
  • 10,264
  • 13
  • 101
  • 209
  • I think you misreaded my answer. I stated clearly that the shown syntax is intended to **discard** the exception. Or do you think is not legitimate ? – CapelliC Nov 24 '13 at 11:59
  • 2
    @CapelliC: We agree on what you wrote. But exactly this catch-all is a permanent source of bugs: There might not only be syntax errors, but other errors. Think of a badly typed list. – false Nov 24 '13 at 12:03
1

this should be the right syntax to 'discard' the exception

?- catch(number_codes(X,"m"),_,true).
true.

?- catch(number_codes(X,"m"),_,false).
false.

to inspect error details, try

?- catch(number_codes(X,"m"),error(E,C),(writeln(E:C),false)).
syntax_error(illegal_number):context(number_codes/2,_G12951)
false.

(I tested in SWI-Prolog...)

CapelliC
  • 59,646
  • 5
  • 47
  • 90