[erlang-questions] Unexpected try/catch behaviour

Bernard Duggan <>
Wed Feb 24 00:36:16 CET 2010


Richard O'Keefe wrote:
> When is it appropriate to use try E of H catch ... end
> instead of try case E of H end catch ... end?
When you want to use tail recursion.
The recursive call to foo() here:

foo(X) ->
    try
        case f(X) of
            A -> foo(A);
            _ -> ok
       end
    catch
       _ -> doom()
    end

Is /not/ tail recursive on account of the catch block.
This, however:

foo(X) ->
    try f(X) of
       A -> foo(A);
       _ -> ok
    catch
       _ -> doom()
    end

/is/ tail recursive, specifically because exceptions thrown in the body
of the try block are not subject to the catch at the end.

(Obviously that code won't work, but you get the idea).

I think.  Going from memory here.

Cheers,

Bernard


More information about the erlang-questions mailing list