programming erlang ch4 - andstudy/forge GitHub Wiki
8> shop:cost(milk3).
=ERROR REPORT==== 11-Jul-2008::08:34:10 ===
Error in process <0.32.0> with exit value: {function_clause,[{shop,cost,[milk3]}
,{erl_eval,do_apply,5},{shell,exprs,6},{shell,eval_loop,3}]}
** exited: {function_clause,[{shop,cost,[milk3]},
{erl_eval,do_apply,5},
{shell,exprs,6},
{shell,eval_loop,3}]} **
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). %% μμΈ μμ±λ¨
-
μμΈ μ²λ¦¬ μ½λ
demo1() -> [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. -
μ€ν κ²°κ³Ό
9> try_test:demo1(). [{1,normal,a}, {2,caught,thrown,a}, {3,caught,exited,a}, {4,normal,{'EXIT',a}}, {5,caught,error,a}]
-
μμ€μ½λ
demo2() -> [{I, (catch generate_exception(I))} || I <- [1,2,3,4,5]]. -
μ€νκ²°κ³Ό
10> try_test:demo2(). [{1,a}, {2,a}, {3,{'EXIT',a}}, {4,{'EXIT',a}}, {5, {'EXIT',{a,[{try_test,generate_exception,1}, {try_test,'-demo2/0-lc$^0/1-0-',1}, {try_test,'-demo2/0-lc$^0/1-0-',1}, {erl_eval,do_apply,5}, {shell,exprs,6}, {shell,eval_loop,3}] } } }]
try Expr
catch
_:_ -> ... λͺ¨λ μμΈλ₯Ό μ²λ¦¬νλ μ½λ ...
end
-
μμ€ μ½λ
demo3() -> try generate_exception(5) catch error:X -> {X, erlang:get_stacktrace()} end. -
μ€ν κ²°κ³Ό
11> try_test:demo3(). {a,[{try_test,generate_exception,1}, {try_test,demo3,0}, {erl_eval,do_apply,5}, {shell,exprs,6}, {shell,eval_loop,3}]}
case f(X) of
{ok,Val} -> do_some_thing_with(Val);
{error,Why} -> %% μ€λ₯λ‘ λ¬΄μμΈκ°λ₯Ό νλ€.
end,
-
μ¬μ©λ²
try my_func(X) catch throw:{thisError,X} -> .. throws:{someOhterError,X) -> ... end -
μ μ
my_func(X) -> case ... of ... -> .. throw({thisError,...)} ... -> .. throw({someOhterError, ...})