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.
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.
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:
This approach allows for explicit error handling and helps make the code more robust and easier to reason about.