Panic in Erlang

Our first example demonstrates how to handle unexpected errors in Erlang. In Erlang, we use exceptions to deal with unexpected situations that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully.

-module(panic_example).
-export([main/0]).

main() ->
    % We'll use throw throughout this site to check for
    % unexpected errors. This is the only program on the
    % site designed to throw an exception.
    throw("a problem"),

    % A common use of exceptions is to abort if a function
    % returns an error value that we don't know how to
    % (or want to) handle. Here's an example of throwing
    % an exception if we get an unexpected error when creating a new file.
    case file:open("/tmp/file", [write]) of
        {ok, _File} -> ok;
        {error, Reason} -> throw({file_error, Reason})
    end.

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

When the first throw 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 the first throw out.

$ erl -noshell -s panic_example main -s init stop
{"a problem"}

Note that unlike some languages which use return values for handling of many errors, in Erlang it is idiomatic to use exceptions for handling exceptional situations, and return values (often in the form of tagged tuples) for expected error conditions.

In Erlang, we typically use pattern matching to handle different return values, including error conditions. For example:

case some_function() of
    {ok, Result} -> 
        % Handle successful case
        do_something_with(Result);
    {error, Reason} -> 
        % Handle error case
        handle_error(Reason)
end.

This approach allows for explicit error handling and helps make the code more robust and easier to reason about.