问题
1> foo:inter(). ** exception error: bad argument in function foo:inter/0 (foo.erl, line 7)
-module(foo).
-compile(export_all).
inter() ->
A = <<"5a">>,
B = binary_to_list(A),
try list_to_integer(B) of
Result -> Result
catch
_ -> {error, bad_integer}
end.
I expected to get {error, bad_integer}.
回答1:
There are 3 types of exceptions in Erlang: error, exit and throw. catch clauses are of the format Type:Pattern. When a Type is not specified, like in your code, only throw exceptions are caught while list_to_integer throws an error. You can catch all error using error:_ or catch any exception using _:_.
1> try list_to_integer("5a") of
1> Result -> Result
1> catch
1> _:_ -> {error, bad_integer}
1> end.
{error,bad_integer}
来源:https://stackoverflow.com/questions/45973322/try-catch-around-list-to-integer-doesnt-catch-error