9 Errors and Error Handling
9.1 Terminology
Errors can roughly be divided into three different types:
- Compile-time errors
- Logical errors
- Run-time errors
A compile-time error, for example a syntax error, should not cause much trouble as it is caught by the compiler.
A logical error is when a program does not behave as intended, but does not crash. An example could be that nothing happens when a button in a graphical user interface is clicked.
A run-time error is when a crash occurs. An example could be when an operator is applied to arguments of the wrong type. The Erlang programming language has built-in features for handling of run-time errors.
When a run-time error occurs in Erlang, execution for the process which evaluated the erroneous expression is stopped. This is referred to as a failure, that execution or evaluation fails, or that the process fails, terminates or exits. Note that a process may terminate/exit for other reasons than a failure.
A process that terminates will emit an exit signal with an exit reason that says something about which error has occurred. Normally, some information about the error will be printed to the terminal.
9.2 Handling of Run-Time Errors in Erlang
9.2.1 Error Handling Within Processes
It is possible to prevent run-time errors from causing the process to terminate by using
catch
, see the Expressions chapter.9.2.2 Error Handling Between Processes
Processes can monitor other processes and detect process terminations, see the Processes chapter.
9.3 Exit Reasons
When a run-time error occurs, the exit reason is a tuple
{Reason,Stack}
.Reason
is an atom indicating the type of error:
Reason Type of error badarg
Argument is of wrong type. badarith
Argument is of wrong type in an arithmetic expression. badmatch
Evaluation of a match expression failed. function_clause
No matching function clause is found when evaluating a function call. case_clause
No matching branch is found when evaluating a case
expression.if_clause
No true branch is found when evaluating an if
expression.undef
The function cannot be found when evaluating a function call. badfun
There is something wrong with a fun. badarity
A fun is applied to the wrong number of arguments. timeout_value
The timeout value in a receive..after
expression is evaluated to something else than an integer orinfinity
.noproc
Trying to link to a non-existing process. nocatch
Trying to evaluate a throw
outside acatch
.system_limit
A system limit has been reached. See Efficiency Guide for information about system limits. Exit Reasons.
Stack
is the stack of function calls being evaluated when the error occurred, given as a list of tuples{Module,Name,Arity}
with the most recent function call first.