Panic in Prolog

In Prolog, we don’t have a direct equivalent of Go’s panic function. However, we can use Prolog’s exception handling mechanism to achieve similar behavior. Here’s how we might implement a similar concept:

:- use_module(library(system)).

main :-
    % We'll use throw/1 throughout this site to check for
    % unexpected errors. This is the only program on the
    % site designed to throw an exception.
    throw(error(a_problem, _)),

    % A common use of exceptions is to abort if a predicate
    % fails unexpectedly. Here's an example of throwing an
    % exception if we get an unexpected error when creating a new file.
    (   create_file('/tmp/file', Stream)
    ->  close(Stream)
    ;   throw(error(file_creation_failed, _))
    ).

% Helper predicate to create a file
create_file(Path, Stream) :-
    catch(
        open(Path, write, Stream),
        Error,
        (format('Error creating file: ~w~n', [Error]), fail)
    ).

Running this program will cause it to throw an exception, print an error message, and exit with a non-zero status.

When the first throw/1 in main is executed, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first throw/1.

To run the program, save it as panic.pl and use the Prolog interpreter:

$ swipl -q -s panic.pl -t main
ERROR: a_problem

Note that unlike some languages which use exceptions for handling of many errors, in Prolog it is idiomatic to use failure and backtracking for control flow, and use exceptions primarily for truly exceptional situations.

In Prolog, we don’t have goroutines as in Go. Prolog’s execution model is based on logical inference and backtracking, which is quite different from Go’s concurrent programming model. However, some Prolog implementations (like SWI-Prolog) do offer support for multi-threading if concurrent execution is needed.