关于异常
exit(why)终止当前进程
throw(why) 抛出异常
erlang:error(why) 相当于内部错误
这三种错误都是用户根据自己的需求来定义的。
下来我们用try...catch函数来处理异常,try...catch的作用是当异常发生的时候,捕获异常,然后继续下面的函数
例子如下:
我们运行程序,看到在捕获异常后,程序会继续执行下去。 例如:test1:test()
如果出现异常,没有捕获的话,程序会终止。例如:test1:test1().
-module(test1).
-export([test/1]).
-export([test1/1]).
test(Num)->
io:format("Num:~p~n",[Num]),
try generate_error(Num) of
Var->
io:format("Var:~p~n",[Var])
catch
Type:Error->
io:format("Type:~p~n",[Type]),
io:format("Error:~p~n",[Error])
end,
io:format("-----------------------------------~n").
test1(1)->
throw(aaaaa),
io:format("-----------------------------------~n");
test1(2)->
exit(aaaaa),
io:format("-----------------------------------~n");
test1(3)->
erlang:error(aaaaa),
io:format("-----------------------------------~n").
generate_error(1)->
aaaaa;
generate_error(2)->
throw(aaaaa);
generate_error(3)->
exit(aaaaa);
generate_error(4)->
erlang:error(aaaaa).