Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

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...)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top