一),Erlang异常产生的原因: 1、函数本身崩溃,自己产生异常。 2、对于if和case子句,找不到匹配发生异常。 3、人工抛出异常 1)、exit(why) 当想要终止当前进程时,就需要用到这个函数。如果这个异常未被捕获, 那么系统会向所有与当前进程相连接的进程广播{'EXIT',Pid,Why}消息。 2)、throw(why) 这个函数用于抛出一个调用者可能会捕获的异常, 3)、erlang:error(Why) 这个函数用于抛出那些崩溃异常。 二)、Erlang异常处理语法 try FuncOrExpressionSequence of Pattern1 [when Guard1]->Expressions1; Pattern2 [when Guard2]->Expressions2; catch ExceptionType:ExPattern1 [whenExGuard1]->Expressions1; ExceptionType:ExPattern2 [whenExGuard2]->Expressions2; ... after AfterExpressions end 语法解释:先执行FuncOrExpressionSequence,如果执行过程中没有异常, 则用Pattern1,Pattern2。。。匹配结果,执行匹配成功的子句。 如果执行抛出异常,则匹配catch后面的异常模式。after后面的语句总是 会执行。不管是结果匹配还是异常匹配,如果没有匹配成功,系统抛出异常。 三),Erlang异常处理实例: -module(exception). -export([start/0]). generate_exception(Num) when Num < 0 -> throw('Num is less than 0'); generate_exception(Num) when Num == 0 -> exit('Num is equal to 0'); generate_exception(Num) when Num == 1 -> erlang:error('Num is equal to 1'); generate_exception(Num) -> Num. test(Num)-> try generate_exception(Num) of Num -> io:format("ok:~p~n",[Num]) catch throw:Message -> io:format("catch throw:~p~n", [Message]); exit:Message -> io:format("catch exit:~p~n", [Message]); error:Message -> io:format("catch error:~p~n", [Message]) after io:format("test run:~p~n",[Num]) end. start()-> test(-1), test(0), test(1), test(2). 执行结果: 3> c(exception). {ok,exception} 4> exception:start(). catch throw:'Num is less than 0' test run:-1 catch exit:'Num is equal to 0' test run:0 catch error:'Num is equal to 1' test run:1 ok:2 test run:2 ok 5>
Erlang异常处理实例demo
最新推荐文章于 2021-03-24 20:19:56 发布