學習Erlang異常處理

-module(catchtest).
-export([trycatch/1,demoFun/1,tryofcatch/1,tryafter/1]).

demoFun(N) ->
	case N of
		0 -> ok;
		1 -> throw(exitwith1);
		2 -> exit(exit2);
		3 -> erlang:error(error3)
	end.


trycatch(N) ->
	try
		demoFun(N)
	catch
		throw:A -> {throwwith,A};
		exit:B  -> {exitwith,B};
		error:C -> {errorewith,C};
		_:_     -> {ohters,others}
	end.

	 
tryofcatch(N) ->
	try
		demoFun(N)
	of      %like case X of
		A-> {ok,A}
	catch
		throw:A -> {throwwith,A};
		exit:B  -> {exitwith,B};
		error:C -> {errorewith,C};
		_:_     -> {ohters,others}
	end.
	
tryafter(N) ->
	try demoFun(N) of
		0 -> {ok,0};
		A -> {ok,A}
	catch
		throw:A -> {throwwith,A};
		exit:B  -> {exitwith,B};
		error:C -> {errorewith,C};
		_:_     -> {ohters,others}
	after
		io:format("Process after ...~n")
	end.
相關文章
相關標籤/搜索