[erlang-questions] Old school exceptions vs. new age one

Richard Carlsson richardc@REDACTED
Mon Apr 28 15:07:57 CEST 2008


Maxim Treskin wrote:
> If I use new-style syntax, I have not detailed exception cause
> explanation, like this:
> 
> 3> try lists:sort([1,2,3]) catch exit:Why -> io:format("~p~n", [Why]) end.
> [1,2,3]
> 4> try lists:sort(abc) catch exit:Why -> io:format("~p~n", [Why]) end.
> ** exception error: function_clause
> 
> But if I use old-style syntax, I have this:
> 
> 5> case (catch lists:sort(abc)) of {'EXIT', Why} -> io:format("~p~n",
> [Why]) end.
> {function_clause,[{lists,sort,[abc]},
>                   {erl_eval,do_apply,5},
>                   {erl_eval,expr,5},
>                   {erl_eval,expr,5},
>                   {shell,exprs,6},
>                   {shell,eval_exprs,6},
>                   {shell,eval_loop,3}]}
> ok

Your try-catch code is not actually catching the exception.
"exit:Why" only matches if the exception is caused by exit(Reason).
"error:Why" matches if you get a runtime error such as function_clause.
"throw:What" matches if the exception is caused by throw(Something).

If you want to catch *all* exceptions, use "Type:Why" or just "_:_".
Also note that using just "Why" is the same as "throw:Why".

When you have caught the exception, you can call erlang:get_stacktrace()
to look at the stack trace if you want to.

New-style syntax is better because the old-style made different kinds
of exception look the same, so you could not separate them. (And it also
had other problems; it could not catch only some exceptions and re-throw
all the others, etc.)

     /Richard





More information about the erlang-questions mailing list