[erlang-questions] Unexpected try/catch behaviour

Richard O'Keefe <>
Thu Feb 25 02:57:18 CET 2010


On Feb 24, 2010, at 9:56 PM, Raimo Niskanen wrote:
> I think this kind of construct is harder to do without the of..catch  
> part:
>
> Handle = resource:open("foo.txt"),
> try resource:read(Handle) of
>    {ok, Data} ->
> 	foo(Data);
>    Error ->
> 	Error
> catch
>    error:Reason ->
> 	{error,Reason}
> after
>    resource:close(Handle)
> end

The tricky thing here is that foo(Data) is
*outside* the scope of the "catch"
*inside* the scsope of the "after"
if I haven't blown all my fuses entirely.

Useful, this is.  Easy to take into acount when reading, it isn't.
I think I'd want some comments, being a Bear of very little Brain.

     Handle = resource:open("foo.txt"),
     try                              	% catch? after?
         resource:read(Handle)		% yes    yes
      of {ok, Data} -> foo(Data)         % no     yes
       ; Error      -> Error
     catch
         error:Reason -> {error,Reason}
     after
         resource:close(Handle)          % no     no
     end

Perhaps nested tries and cases might actually be easier to read.



More information about the erlang-questions mailing list