[erlang-questions] Try-catch-after considered harmful.

Joe Armstrong erlang@REDACTED
Mon Nov 24 10:45:23 CET 2014

Is it just me, or is something wrong about try-catch-after?

I keep reading a lot of articles, and replying to private posts
concerning the correct us of try-catch-after.

My first response is "don't use use try-catch-otherwise at all" let
the process crash and let some other process fix up any damaging
consequences of the crash.

The best was to write error handling code is to write no error
handling code at all.

At a first approximation, all the libraries are designed to be used
this way.  If you open a resource like a file/socket/ets table/dets
table/database table then if your program crashes the resource (which
is represented by a process) will detect the crash and is supposed to
"do the right thing" and clean up behind you.

The try-catch syntax was deliberately chosen to be reminiscent of
Java, the idea being that if you understood this try-catch consequence
in Java you'd easily understand the Erlang code.

The problem I see with this is that programmers with previous
experience in Java are tempted to blindly convert sequential try-catch
code in Java into sequential try-catch code in Erlang, but this is
almost always the wrong thing to do.

Beginners should be forbidden to use try-catch - the Erlang "way" is
to spawn_link a regular process (ie a process that does not trap
exits) and just let that process die if anything goes wrong. There
should be no error trapping code in the spawned process. Call
exit(Why) in every place where the behaviour is unspecified.

The process doing the spawn_link should trap exits and report errors
in the child processes. This is what all the supervisor and
gen_my_aunties_hat stuff does in the standard libraries.

If you really-really-really understand what changing the flow of
execution in sequential code does then by all means try-catch-after -
but the best advice is not to use it at all.

There should really be a compiler warning -

** try-catch-after used - this is probably not the right way to do things



More information about the erlang-questions mailing list