erlang中的错误处理

erlang中错误大体分为四种:

1. 编译错误
2. 逻辑错误
3. 运行时错误
4. 用户代码生成的错误

编译错误,主要是编译器检测出的代码语法错误
逻辑错误,是指程序没有完成预期的工作,属于开发人员的问题
运行时错误,是指erlang运行时抛出的错误,比如对非数据类型执行算术运算,erlang运行时会捕获异常,并抛出。在erlang中,这类异常的类型为error
用户自定义错误,是指通过exit/1或者throw/1生成

我们把运行时错误以及用户抛出的错误称为异常(exception),他们具有三种类型:throw, error, exit。
error型异常,通过erlang:error/1, 2生成,也可以使用早期的erlang:fault/1, 2
throw型异常,通过throw/1生成
exit型异常,通过exit/1生成

在erlang中,进程内的异常可以通过try, catch来进行捕获处理。
推荐使用try,其为新添加的语法。进程间的异常可以通过监督树(supervisor tree),监控进程(monitor)来实现。

badarg 参数错误,参数格式或类型错误
badarith 算术表达式错误,算术表达式中含有错误的参数
{badmatch,V} 模式匹配错误,V指具体的发生匹配错误的数值
function_clause 函数子句错误,没有找到匹配的函数子句
{case_clause,V} case匹配错误,没有找到匹配的case pattern
if_clause if子句错误,没有找到为ture的if子句
{try_clause,V} try匹配错误,执行try时,没有找到匹配的pattern
undef 函数未定义错误
{badfun,F} 函数错误
{badarity,F} 函数参数个数错误
timeout_value 超时参数错误,在receive.. after语法中,after对应的超时数据错误(应为不小于0的integer或infinity
noproc Process 错误,Process不存在
{nocatch,V} throw未被catch
system_limit 系统限制错误,某些性能或数据达到系统极限

try 语法


try Exprs [of
Pattern1 [when GuardSeq1] ->
Body1;
...;
PatternN [when GuardSeqN] ->
BodyN
catch
[Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
ExceptionBody1;
...;
[ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
ExceptionBodyN
end


如果try Exprs后没有of部分,则默认为Exprs的返回值。
如果在of部分或者catch部分,发生了异常,那么异常将不被处理,直接抛出。
下面的代码可以让你充分的学习,理解try语法。
test_try.erl 下载代码


-module(test_try).
-compile([export_all]).

-author('cheng litaocheng@gmail.com').

%% @spec test(F1, F2) -> Result
%% @doc evaluate the F , use the try to catch all kinds of error
%% F1 the Expression to be catch exception
%% F2 the Expression evaluate in the catch section
test(F1, F2) when (is_function(F1, 0) andalso is_function(F2, 0)) ->
try F1()
catch
throw:X ->
{{caught, throw, X}, F2()};
exit:X ->
{{caught, exit, X}, F2()};
error:X ->
{{caught, error, X}, F2()}
after
io:format("always evaluate the after body~n")
end.


运行:


21> c(test_try).
{ok,test_try}
22> test_try:test(fun() -> throw(hello) end, fun() -> ok end).
always evaluate the after body
{{caught,throw,hello},ok}
23> test_try:test(fun() -> exit(hello) end, fun() -> ok end).
always evaluate the after body
{{caught,exit,hello},ok}
24> test_try:test(fun() -> erlang:error(hello) end, fun() -> ok end).
always evaluate the after body
{{caught,error,hello},ok}
25> test_try:test(fun() -> erlang:error(hello) end, fun() -> throw(exception_in_catch) end).
always evaluate the after body
** exception throw: exception_in_catch
in function test_try:test/2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值