Erlang 编程/错误
外观
我们可以用 throw 和 catch 来处理错误。在这个例子中,参数的值会导致错误,从而抛出异常。函数 g() 只有在参数大于 12 时才会正常工作。如果参数小于 13,则会抛出异常。我们尝试在 start() 中调用 g()。如果我们遇到问题,则会在 start() 中的“case catch”结构中捕获异常。
示例程序列表
-module(catch_it).
-compile(export_all).
%
% An example of throw and catch
%
g(X) when X >= 13 ->
ok;
g(X) when X < 13 ->
throw({exception1, bad_number}).
%
% Throw in g/1
% Catch in start/1
%
start(Input) ->
case catch g(Input) of
{exception1, Why} ->
io:format("trouble is ~w ", [ Why ]);
NormalReturnValue ->
io:format("good input ~w ", [ NormalReturnValue ] )
end.
%
%============================================================== >%
% sample output:
%
8> c(catch_it).
{ok,catch_it}
%
9> catch_it:start(12).
trouble is bad_number ok
%
10> catch_it:start(13).
good input ok ok