idiom for clearing up resources?

Vladimir Sekissov svg@REDACTED
Mon Aug 25 14:57:00 CEST 2003


Good day,

I often use the following construct in such cases:

myfunc() ->
 Ret=
  case catch
    begin
      ok = file:make_dir("c:/tmp/foo"),
      %% do some stuff
      {ok, Res}
    end of
    R={ok, _} ->
      R;
    Other ->
      better_error(Other)
  end,
  %% cleanup
  (catch file:del_dir("c:/tmp/foo")),
 Ret.

better_error({'EXIT', {{badmatch, Error}, _}}) ->
  better_error(Error);
better_error({'EXIT', Error}) ->
  better_error(Error);
better_error(Error) when is_tuple(Error),
			 element(1,Error) == error ->
  Error;
better_error(Error) ->
  {error, Error}.

Best Regards,
Vladimir Sekissov

D.WILLIAMS> Is there an idiom for initializing and clearing up resources
D.WILLIAMS> (e.g. files) needed by an Erlang function, in such a way that the
D.WILLIAMS> clear-up code gets called even in the face of an error?
D.WILLIAMS> 
D.WILLIAMS> e.g.
D.WILLIAMS> 
D.WILLIAMS> myfunc() ->
D.WILLIAMS> 	ok = file:make_dir("c:/tmp/foo"),
D.WILLIAMS> 	% do some stuff
D.WILLIAMS> 	ok = file:del_dir("c:/tmp/foo").
D.WILLIAMS> 
D.WILLIAMS> I want the last line to be called even if "do some stuff" crashes.
D.WILLIAMS> Basically, coming from a C++ background, this is the code I would
D.WILLIAMS> have put in something's destructor, and I am wondering what Erlangers
D.WILLIAMS> do...
D.WILLIAMS> 
D.WILLIAMS> Cheers,
D.WILLIAMS> 
D.WILLIAMS> Dominic.



More information about the erlang-questions mailing list