[erlang-questions] Unexpected try/catch behaviour

David Mercer dmercer@REDACTED
Thu Feb 25 16:36:27 CET 2010


On February 24, 2010, Richard O'Keefe wrote:
> 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.

That is a good point.  Sounds like the ordering of the clauses should be
changed from try.of.catch.after to try.catch.of.after.  Try this on for
size:

	try resource:read(Handle)
		catch
			error:Reason -> {error,Reason}
		of
			{ok, Data} -> foo(Data);
			Error -> Error
		after
			resource:close(Handle)
	end

No, that doesn't really work, since it leads you to believe that the "of"
applies also to the result of the "catch."  Would dispensing with the catch
clause entirely help?  I'm not sure that a valid "*catch* match" (with the
colon) is a valid "*of* match," so maybe we can mix-and-match:

	try resource:read(Handle)
		of
			{ok, Data} -> foo(Data);
			Error -> Error;
			error:Reason -> {error,Reason}
		after
			resource:close(Handle)
	end

Certainly that seems to convey the meaning better.  Is it foolproof?

Cheers,

David



More information about the erlang-questions mailing list