[erlang-questions] When to throw..when to case...when to...

Mike Oxford moxford@REDACTED
Tue Apr 26 20:55:36 CEST 2011


I was going through the uds_drv included in the OTP distribution.

Here's a snippet of code...

--snip
command(Port, Command, Parameters) ->

    SavedTrapExit = process_flag(trap_exit,true),
    case (catch erlang:port_command(Port,[Command | Parameters])) of
	true ->
	    receive
		{Port, {data, [Command, $o, $k]}} ->
		    process_flag(trap_exit,SavedTrapExit),
		    {ok, Port};
		{Port, {data, [Command |T]}} ->
		    process_flag(trap_exit,SavedTrapExit),
		    {ok, T};
		{Port, Else} ->
		    process_flag(trap_exit,SavedTrapExit),
		    exit({unexpected_driver_response, Else});
		{'EXIT', Port, normal} ->
		    process_flag(trap_exit,SavedTrapExit),
		    {error, closed};
		{'EXIT', Port, Error} ->
		    process_flag(trap_exit,SavedTrapExit),
		    exit(Error)
	    end;
	{'EXIT', {badarg, _}} ->
	    process_flag(trap_exit,SavedTrapExit),
	    {error, closed};
	Unexpected ->
	    process_flag(trap_exit,SavedTrapExit),
	    exit({unexpected_driver_response, Unexpected})
    end.

--end snip

I understand setting trap_exit in the process.  They're also embedding a
catch in the Expr for the case.

Now, whomever wrote this knows more about Erlang than I do, as I've only
been doing this for a couple of weeks.
What confuses me is....
1) Why set trap_exit here instead of in the init()?  Is it because a
sync-call would be executed in the context of the caller and not be caught
by the init()'d trap_exit?
2) Why catch port_command, feed it to case and then handle it?  Why not just
put it in a try-catch-final block to reset the trap_exit state?  Is it
because this was written before R10B2 when the try-catch stuff was
introduced?

In general, when should you throw and exception vs returning a value?  When
should your protect your code with try/catch vs using a case?  Are there any
hard and fast rules or is it purely determined by the function being called?

TiA!

-mox
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20110426/d4c35415/attachment.htm>


More information about the erlang-questions mailing list