safe catch

Ulf Wiger <>
Mon Mar 25 13:16:40 CET 2002



I recently ran across a (user) bug involving catch. The bug was
such that one could sometimes mistake a deliberate {'EXIT',
Reason} return value from for a real crash, with unexpected
results. As the code was found in a generic library function, it
had to be fixed.


I decided to put in the following construct:

  case catch {ok, f()} of
     {'EXIT', Reason} ->
        handle_EXIT(Reason);
     {ok, Result} ->
        Result
  end.


If all one cares about is handling the case where the caught
function really exits, I don't really see a reason *not* to
consistently use the above pattern.

Of course (sigh), the caught function could still mess things up
by calling throw({ok, {'EXIT', Reason}}), but there should
perhaps be a limit to the level of stupidity one needs expect
from the average programmer. Here's a paranoid (but more
expensive) version:

  Ref = make_ref(),
  case catch {Ref, f()} of
     {'EXIT', Reason} ->
         handle_EXIT(Reason);
     {Ref, Result} ->
         Result
  end.

Does anyone have a suggestion for a fool proof and "free" way to
do this?

(Not that I personally couldn't live with the first alternative.)

/Uffe




More information about the erlang-questions mailing list