Erlang笔记(08) - try catch

1. try ... catch 句型

try FuncOrExpressionSequence of
	Pattern1 [when Guard1] ->
		ExpressionBody1;
	Pattern2 [when Guard2] ->
	        ExpressionBody2
catch
	[ExceptionType:]ExceptionPattern1
		[when ExceptionGuardSeq1] ->
		ExceptionBody1;
	[ExceptionType:]ExceptionPatternN
		[when ExceptionGuardSeqN] ->
		ExceptionBodyN
after
        AfterExpressions
end.

  1. try ... catch 工作原理
    • 对 FuncOrExpressionSequence 先求值
      • 如果不产生异常,那么它的返回值就对模式Pattern1, Pattern2... 进行模式匹配。如果匹配成功,模式之后的表达式的值就是 try ... catch 的返回值
      • 如果产生异常,就会逐个匹配 catch 下的 Expattern1 等模式。ExceptionType 是原子throw,exit error 中的一个。未标明 ExceptionType,默认为 throw.
    • after 为可选项,它后面的代码,用于执行完 FuncOrExpressionSequence 后的清理工作。无论是否抛出异常,这段代码一定都会被执行。
  2. 举例
  3. demol() -> 
    	[catcher(I) || I <- [1,2,3,4,5]].
    
    catcher(N) ->
    	try generate_exception(N) of
    		Val -> {N, normal, Val}
    	catch
    		throw:X -> {N, caught, thrown, X};
    		exit:X -> {N, caught, exited, X};
    		error:X -> {N, caught, error, X}
    	end.
    	
    generate_exception(1) -> a;
    generate_exception(2) -> throw(a);
    generate_exception(3) -> exit(a);
    generate_exception(4) -> {'Exit', a};
    generate_exception(5) -> erlang:error(a).
    
    % output:
    % [{1, normal, a},
    % {2, caught, thrown, a},
    % {3, caught, exited, a},
    % {4, normal, {'Exit', a}},
    % {5, caught, error, a}]
  4. 捕获所有可能异常
    • try Expr
    • catch
    •     _:_ -> ...
    • end.

2. To-Be-Added...


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值