[erlang-questions] Try-catch-after considered harmful.
Mon Nov 24 10:55:21 CET 2014
There is at least one exception to this, and it has to do with sockets.
Closing the socket on crash is fine but most protocols require you to
send an error response before you go away (4xx or 5xx with "close"
option in HTTP1, GOAWAY in HTTP2, for example). Sending this error is
almost always a good thing because it makes sure the client knows the
connection gets closed and will not get stuck with a half-open scenario.
There is no way to send these responses from another process using
spawn_link because the socket dies with the process that died.
Otherwise yes, for most use cases I would agree with you, and would also
add the lonely catch to the list of constructs to avoid (perhaps even
more than try-catch-after).
On 11/24/2014 11:45 AM, Joe Armstrong wrote:
> 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
> erlang-questions mailing list
More information about the erlang-questions