erlang精要(27)-异常处理
生活随笔
收集整理的這篇文章主要介紹了
erlang精要(27)-异常处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、拋出異常throw
98> c(learnerl). learnerl.erl:7: Warning: variable 'X' is unused {ok,learnerl} 99> learnerl:activation({sss,1.243}). {unfound_activation_fun,sss,1.243} 100> learnerl:activation({sigmoid,1.243}). 0.7760857759636308 101> -module(learnerl). -export([activation/1]).init(C_type)->case C_type ofsigmoid->fun(X)-> 1 /(1+math:exp(-X)) end;_-> fun(X)-> throw(unfound_activation_fun) endend.activation({C,X})->Active_fun=init(C),try Active_fun(X)catchthrow:E->{E,C,X}end.2、產生錯誤error
25> c(learnerl). {ok,learnerl} 26> learnerl:compute_sqrt(-200). {badarith,-200} 27> learnerl:compute_sqrt(200). 14.142135623730951 28> c(learnerl). {ok,learnerl} 29> learnerl:compute_sqrt(200). 14.142135623730951 30> learnerl:compute_sqrt(-200). {error,badarith} 31> -module(learnerl). -export([compute_sqrt/1]).sqrt(X)->math:sqrt(X).compute_sqrt(X)->try sqrt(X) catcherror:E->{error,E}end.3、綜合例子
92> c(learnerl). {ok,learnerl} 93> learnerl:compute_sqrt(209). throw:只接收不大于200的數=>209 ok 94> learnerl:compute_sqrt(20). 4.47213595499958 95> learnerl:compute_sqrt(-20). error:不能小于0=>-20 ok 96> learnerl:compute_sqrt(200). 14.142135623730951 97> learnerl:compute_sqrt(0). 0.0 98> -module(learnerl). -export([compute_sqrt/1]).sqrt(X) when (X>=0) and (X=<200) ->math:sqrt(X); sqrt(X) when X >200 ->throw("只接收不大于200的數"); sqrt(X) when X <0 ->error("不能小于0").compute_sqrt(X)->try sqrt(X) catcherror:E->io:format("~p:~ts=>~p~n",[error,E,X]);throw:Tw->io:format("~p:~ts=>~p~n",[throw,Tw,X])end.4、終止進程
exit(Why)
終止進程,產生{‘EXIT’,PId,Why}并廣播地給當前進程鏈接的所有進程
總結
以上是生活随笔為你收集整理的erlang精要(27)-异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java如何将String转换为enum
- 下一篇: 异常:Get请求提交过来的中文参数乱码