Common errors

A beginner meets the same dozen messages again and again, and each one names its cause once you can read it. An exception is a class and a reason, and the let it crash lesson shows the classes; this page is the field guide to the reasons, with a real run of each and the fix that removes it.

Read the message

A report has the shape Class:Reason. The class is error, throw or exit; the reason is a term, and its shape is the clue. The shell adds a sentence and a stack trace, but the term is what a catch clause matches, so the term is what a program reads. The catch form in the programs below prints both parts, which is the first thing to do with an error you do not know.

Arithmetic and arguments

badarith is an arithmetic expression with no value, such as a division by zero, and badarg is an argument of the wrong type or shape. The program reads its values from a file, so the compiler cannot see the bad ones and refuse the calls before the run:

reasons.erl

-module(reasons). -export([main/0]). main() -> ok = file:write_file("input.txt", <<"0 10x">>), {ok, Bin} = file:read_file("input.txt"), [Zero, Text] = binary:split(Bin, <<" ">>, [global]), report("badarith", fun() -> 1 / binary_to_integer(Zero) end), report("badarg", fun() -> binary_to_integer(Text) end), io:format("enoent is a value: ~p~n", [file:read_file("missing.txt")]), ok = file:delete("input.txt"). report(Name, Fun) -> try Fun() of Value -> io:format("~s: ~p~n", [Name, Value]) catch Class:Reason -> io:format("~s: ~p:~p~n", [Name, Class, Reason]) end.

erlc reasons.erl

erl -noshell -eval 'reasons:main(), halt().'

badarith: error:badarith badarg: error:badarg enoent is a value: {error,enoent}

The fixes are local. A divisor is checked before the division, or the function answers {error, division_by_zero} as the let it crash lesson writes it. An argument is converted once at the edge of the program and never again inside. And enoent is not an exception at all: file:read_file/1 answers {error, enoent}, which the caller matches. Treating a missing file as a crash is the mistake, not the missing file.

Calls and processes

The second family is about a call that cannot reach anything. noproc is a gen_server call to a name that nobody registered, undef is a call to a function that is not loaded, and badmatch is a pattern on the left that the value on the right does not match. The program calls all three and prints the reason term:

crash.erl

-module(crash). -export([main/0]). main() -> report("noproc", fun() -> gen_server:call(missing_server, ping) end), report("undef", fun() -> Module = list_to_atom("lists"), Function = list_to_atom("no_such_function"), apply(Module, Function, []) end), report("badmatch", fun() -> {ok, Value} = binary_to_term(term_to_binary({error, missing})), Value end). report(Name, Fun) -> try Fun() of Value -> io:format("~s: ~p~n", [Name, Value]) catch Class:Reason -> io:format("~s: ~p:~p~n", [Name, Class, Reason]) end.

erlc crash.erl

erl -noshell -eval 'crash:main(), halt().'

noproc: exit:{noproc,{gen_server,call,[missing_server,ping]}} undef: error:undef badmatch: error:{badmatch,{error,missing}}

A noproc means the server is not running, or the name is not the one it registered: start it first, or register it under the name the caller uses. An undef means the module or the function is not on the code path of this node, which in a shell is usually a forgotten erlc or a -pa that points elsewhere. A badmatch names the value that arrived, which is the fastest kind of error to fix: the pattern and the value disagree, and the message shows both.

The compiler's own messages

Some errors never reach the runtime. An unused variable is a warning, and the compiler of this course turns warnings into errors with -Werror, so the build stops on the line. The body below is the fragment of a module whose variable is never used, and the lines under it are the compiler's answer, quoted from the run of erlc -Werror on that module:

main() -> Spare = 42, io:format("done~n").

compile: warnings being treated as errors unused.erl:5:5: variable 'Spare' is unused % 5| Spare = 42, % | ^

The fix is to use the value or to say that it is unused: _Spare silences the warning for a name you keep for the reader, and a bare _ for a value nobody needs. Three more messages from the same stage: function foo/1 undefined means a call to a function that is not defined in the module or not exported from the other one; variable 'X' is unbound means the name is used before any clause binds it, often because of a typo; and syntax error before: end is usually a missing ., a missing ; between clauses or one end too few. The compiler names the line, the column and the token, and the fix is on that line or the one before it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the shape of an exception a catcher reads?

    Answer

    A class and a reason

    The class is error, throw or exit, and the reason is the term that names the failure.

  2. What does badarith mean?

    Answer

    An arithmetic expression with no value

    A division by zero is the usual cause, and the reason is the atom badarith.

  3. What does file:read_file/1 answer for a file that does not exist?

    Answer

    {error, enoent}

    A missing file is a value the caller matches, not a crash.

  4. What does a gen_server call to an unregistered name raise?

    Answer

    exit:{noproc, ...}

    The call exits with a noproc reason, which is why a caller wraps it in a try.

  5. What does undef mean?

    Answer

    The function is not loaded or not exported

    The runtime could not find the module or the function on the code path of the node.

  6. Why does this course compile with -Werror?

    Answer

    To turn a warning into a failed build

    An unused variable or a shadowed name is a real defect in a lesson, so it stops the build.

  7. What does this module print? -module(q1). -export([main/0]). main() -> ok = file:write_file("q1.txt", <<"ten">>), {ok, Bin} = file:read_file("q1.txt"), R = try binary_to_integer(Bin) catch C:E -> {C, E} end, io:format("~p~n", [R]).

    Answer

    {error,badarg}

    The text is not a number, so the call raises an error with the reason badarg.

  8. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~p~n", [catch throw(stop)]).

    Answer

    stop

    The catch expression answers the value of a throw without a tuple around it.

  9. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~p~n", [file:read_file("no_such_file.txt")]).

    Answer

    {error,enoent}

    The file does not exist, and the call answers the error tuple with enoent.

  10. What does this module print? -module(q4). -export([main/0]). main() -> R = try gen_server:call(missing, ping) catch exit:Reason -> {exit, Reason} end, io:format("~p~n", [element(1, element(2, R))]).

    Answer

    noproc

    The call exits with {noproc, ...}, and the first element of the reason names it.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container. The unused variable block shows the compiler error on purpose.

Автор статьи: Arthur Isaev

Изображение баннера