Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one should I use exit, error or throw?

Tags:

erlang

Could you tell me when to use throw, exit and error?

1> catch throw ({aaa}).
{aaa}
2> catch exit ({aaa}).
{'EXIT',{aaa}}
3> catch gen_server:call(aaa,{aaa}).
{'EXIT',{noproc,{gen_server,call,[aaa,{aaa}]}}}
4> catch exit("jaj")
{'EXIT',"jaj"}
like image 267
Chen Yu Avatar asked Nov 29 '12 03:11

Chen Yu


People also ask

What's the difference between throw error (' MSG ') vs throw new error (' MSG ')?

catch statement with having throw Error(). This code will do that the 'msg' error is thrown in the try-block which will be get executed by catch statements. new Error object: It captures several properties of the place where the error happened. It exposes an error event with two parameters name & message.

Does throwing error exit function?

It does, yes.

Why would you want to throw an exception?

Exceptions should be used for exceptional situations outside of the normal logic of a program. In the example program an out of range value is likely to be fairly common and should be dealt with using normal if-else type logic. (See the programming exercises.)

What is a thrown error?

Throwing an error lets you indicate that something unexpected happened and the normal flow of execution can't continue. You use a throw statement to throw an error.


1 Answers

There are 3 classes which can be caught with a try ... catch: throw, error and exit.

  • throw is generated using throw/1 and is intended to be used for non-local returns and does not generate an error unless it is not caught (when you get a nocatch error).

  • error is generated when the system detects an error. You can explicitly generate an error using error/1. The system also includes a stacktrace in the generated error value, for example {badarg,[...]}.

  • exit is generated using exit/1 and is intended to signal that this process is to die.

The difference between error/1 and exit/1 is not that great, it more about intention which the stacktrace generated by errors enhances.

The difference between them is actually more noticeable when doing catch ...: when throw/1 is used then the catch just returns the thrown value, as is expected from a non-local return; when an error/1 is used then the catch returns {'EXIT',Reason} where Reason contains the stacktrace; while from exit/1 catch also returns {'EXIT',Reason} but Reason only contains the actual exit reason. try ... catch looks like it equates them, but they are/were very different.

like image 166
rvirding Avatar answered Sep 24 '22 16:09

rvirding