Throw or return a tuple

Ulf Wiger <>
Sat Aug 13 23:15:55 CEST 2005

Den 2005-08-13 22:58:47 skrev <>:

> The try/catch syntax seems to be a lot ebtter than case catch.  Does it  
> still have some common limitations that one should watch out for?

Well, one thing to consider if you decide to use
"assertion-style" programming with pattern-matching,
is that it can sometimes be difficult to know where
in a function a crash occured:

copy_file(F1, F2) ->
   {ok, Fd1} = file:open(F1, read),
   {ok, Fd2} = file:open(F2, write),
   copy_chunks(Fd1, Fd2).

If the above function exits with e.g. a
{badmatch, {error, eaccess}}, it can be difficult
to know which operation caused the problem.

There are ways to get around this. Either refactor,
and make (in this case) a helper function for open(),
or find innovative ways to wrap your statements:

copy_file(F1, F2) ->
   {_, {ok, Fd1}} = {F1, file:open(F1, read)},
   {_, {ok, Fd2}} = {F2, file:open(F2, write)},
   copy_chunks(Fd1, Fd2).

would instead give you an error message like this one:

** exited: {{badmatch,{"foo.txt",{error,enoent}}},
              {shell,eval_loop,3}]} **

Ulf Wiger

More information about the erlang-questions mailing list