Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 40 ยท Data Structures and Parsing

Input, Output and Error Handling

Learn Prolog input and output with write, format, read and streams, work with files, and handle errors with catch/3 and throw/1, ISO error terms, must_be/2 and clean-up predicates.

So far your programs have communicated through the toplevel: you type a query, Prolog prints the bindings. Real programs also print results, read user input, work with files and cope with things going wrong. This lesson covers output predicates, input, streams and files, and finishes with Prolog's exception mechanism, catch/3 and throw/1, which is what turns errors from crashes into something you can handle.

Writing terms

Predicate What it prints
write(T) the term, in readable form
print(T) the term, using portray hooks and quoting
writeq(T) the term with quotes where needed, so it can be read back
write_canonical(T) operator-free, quoted, ignores operators
nl a newline
tab(N) N spaces
format(Template, Args) formatted output (see Atoms, Strings and Characters)
PROLOG
?- write('Hello World'), nl.
Hello World

?- writeq('Hello World'), nl.
'Hello World'

?- write_canonical(1 + 2), nl.
+(1,2)

Use write for output meant for people and writeq for output that a program will read back (a log file, a saved fact). For anything with layout, use format/2:

PROLOG
?- format("~w is ~d years old~n", [ann, 31]).
ann is 31 years old

To print to the error stream, name it: format(user_error, "warning: ~w~n", [Msg]). To capture output into text instead, use with_output_to(string(S), Goal) or format(atom(A), ...).

Reading input

read(Term) reads one Prolog term from standard input. The term must end with a full stop. At the end of the input it returns the atom end_of_file.

PROLOG
?- read(X).
|: foo(bar).
X = foo(bar).

For ordinary text, read lines or characters instead:

PROLOG
?- read_line_to_string(user_input, Line).
|: hello there
Line = "hello there".

read_line_to_string/2 returns the atom end_of_file when no more lines exist. Related predicates are get_char/1, peek_char/1, read_term/2 (with options such as variable_names(Vs)), read_string/3 and read_line_to_codes/2.

The classic loop reads until end of input, using repeat and a cut (see Negation, If-Then-Else and Loops) or, better, a recursive predicate:

PROLOG
process_lines(Stream) :-
    read_line_to_string(Stream, Line),
    (   Line == end_of_file
    ->  true
    ;   format("got: ~w~n", [Line]),
        process_lines(Stream)
    ).

The recursion is in tail position, so it runs in constant stack space however long the input is.

Streams and files

All I/O goes through streams. The standard ones are user_input, user_output and user_error. To use a file, open it, work with the stream, and close it:

PROLOG
write_report :-
    open('report.txt', write, Out),
    format(Out, "Total: ~d~n", [42]),
    close(Out).

read_report(Text) :-
    read_file_to_string('report.txt', Text, []).

The modes are read, write, append and update. Because an error between open and close would leak the file, prefer setup_call_cleanup/3, which always runs the cleanup goal:

PROLOG
copy_first_line(File) :-
    setup_call_cleanup(
        open(File, read, In),
        read_line_to_string(In, Line),
        close(In)),
    writeln(Line).

The older "Edinburgh" style, see/1, tell/1, seen/0 and told/0, switches the current input or output and still appears in textbooks; the stream style above is clearer and safer.

For whole files, read_file_to_string/3, read_file_to_terms/3 and read_file_to_codes/3 do all of this in one call. Use consult/1 or load_files/2 to load a file as a program.

Exceptions

When something goes wrong, such as an unbound variable in arithmetic or a call to an undefined predicate, Prolog throws an exception. An exception unwinds the call stack, abandoning every goal in progress, until a matching catch/3 is found. With none, the toplevel prints the error.

PROLOG
catch(Goal, Catcher, Recovery)

catch/3 runs Goal. If it throws a term that unifies with Catcher, bindings made by Goal are undone and Recovery runs. If Goal completes normally, catch/3 behaves exactly like Goal, including backtracking into it.

PROLOG
?- catch(X is foo + 1, error(Formal, _), true).
Formal = type_error(evaluable, foo/0).

?- catch(atom_length(_, _), error(Formal, _), true).
Formal = instantiation_error.

?- catch(no_such_predicate, error(Formal, _), true).
Formal = existence_error(procedure, no_such_predicate/0).

?- catch(throw(my_problem), Caught, true).
Caught = my_problem.

You can throw any term with throw/1. By convention, system errors have the shape error(Formal, Context), where Formal is one of the ISO error terms:

Formal Meaning
instantiation_error a required argument is unbound
type_error(Type, Culprit) an argument has the wrong type
domain_error(Domain, Culprit) the right type but an unacceptable value
existence_error(Kind, What) the procedure or file does not exist
permission_error(Action, Type, Culprit) an operation is not allowed
evaluation_error(Reason) arithmetic failed, for example zero_divisor
resource_error(What) memory or other limit exceeded

When writing your own library predicates, follow the same convention so that callers can handle your errors like system ones. SWI-Prolog's must_be(Type, Value) does the checking for you: must_be(integer, foo) throws type_error(integer, foo), and must_be(integer, _) throws instantiation_error.

The stand-in engine below supports throw, catch and the arithmetic and existence errors, so you can see unwinding in action. Prolog is not available on this site, so this is a Python model.

Python catch and throw (Python stand-in engine)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last query shows what an uncaught exception looks like: the query ends with an error rather than false. A failure means "no (more) solutions"; an exception means "something unexpected happened". Keep the two apart: do not throw to say "not found", and do not fail where the caller made a mistake.

Clean-up and logging

setup_call_cleanup(Setup, Goal, Cleanup) guarantees that Cleanup runs when Goal succeeds deterministically, fails, throws or is cut. Use it for files, sockets and locks. print_message(Kind, Term) sends a message through the system's message layer (kinds error, warning, informational), so users can redirect or translate it, and assertion(Goal) throws an assertion_failed exception when your own sanity check is false.

Python Reading lines until end of input (Python model)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Forgetting the final full stop when typing a term for read/1; Prolog waits for more input.
  • Using write/1 for output you want to read back later. Use writeq/1 or print/1 so atoms with spaces are quoted.
  • Leaving files open after an error. Use setup_call_cleanup/3.
  • Catching every exception with a bare variable (catch(G, _, true)) and silently hiding bugs. Match the error you expect, or rethrow what you do not recognize.
  • Using format with the wrong number of arguments; the error appears at run time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does read(X) need at the end of what you type?

    read/1 reads a complete Prolog term, which must end with a full stop.
  2. 2. What happens when a goal inside catch(G, error(F, _), R) throws error(type_error(a, b), c)?

    The thrown term unifies with the catcher, bindings made by G are undone and the recovery goal runs.
  3. 3. Which is the best way to make sure a file is closed even if reading throws?

    setup_call_cleanup runs the cleanup goal on success, failure, exception or cut.
  4. 4. What is the difference between failure and an exception?

    Failing is a normal answer ('no'); exceptions mean the program asked something it could not answer.

Summary

  • write, writeq, print, format and nl produce output; read/1, read_line_to_string/2 and get_char/1 take input.
  • All I/O uses streams: user_input, user_output, user_error and files opened with open/3.
  • catch/3 and throw/1 implement exceptions; system errors look like error(Formal, Context).
  • Use must_be/2 to validate arguments and setup_call_cleanup/3 to release resources.
  • Failure and exceptions mean different things; use each for its purpose.

Next: Constraint Logic Programming Basics