本文介绍了尝试捕获list_to_integer不会捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1> foo:inter()。
**异常错误:函数foo:inter / 0(foo.erl,第7行)中的错误参数

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.

我期望得到{error,bad_integer}。

I expected to get {error, bad_integer}.

推荐答案

有在Erlang中:错误退出抛出 catch 子句的格式为 Type:Pattern 。当未指定 Type 时(如您的代码中),只有 throw 异常会被捕获,而 list_to_integer 引发错误。您可以使用 error:_ 捕获所有错误或使用 _:_ 。

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}

这篇关于尝试捕获list_to_integer不会捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 01:08