Try catch around list_to_integer doesn't catch error

喜夏-厌秋 提交于 2019-12-11 05:18:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!