[erlang-questions] When to throw..when to case...when to...
Mihai Balea
mihai@REDACTED
Tue Apr 26 22:01:28 CEST 2011
On Apr 26, 2011, at 2:55 PM, Mike Oxford wrote:
>
> 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?
I'd say this code was designed to be called from a user's process. Setting trap_exit would override the user's own trap_exit flag, which is not what you'd normally want. So the author saves the previous trap_exit value, enables it, then restores it before returning. The reason for temporarily enabling trap_exit is to catch port code terminations (crashes) as a response to a specific command.
> 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?
Most likely. I don't see why anybody would avoid using a try/catch/after nowadays. Especially since restoring trap_exit in an after body would save about 5-6 lines of code.
>
> 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?
It is a matter where personal preferences play a large part. My interpretation is to return an error value when a function fails as part of normal operation and an exception when things might indicate a bug in code. Consider writing to a file: read only access or disk full should be returned as error values; wrong parameters (such as wrong types, etc) would warrant an exception.
Mihai
More information about the erlang-questions
mailing list