`

erlang异常--try...catch

阅读更多
触发异常
throw(Term)
exit(Reason)
erlang:error(Reason)

特列:exit(normal),进程调用它所跑出的异常不会被捕获,该进程正常终止


try...catch
try
    unsafe_fun()
catch
    ErrType:Reason ->
        do_something()
end.


try...of...catch
try
    unsafe_fun()
of
    O ->
        io:format("do nothing");
    N ->
        do_something_with(N)
catch
    _:_ ->
        do_something()
end

of...之间的内容,不在try的保护范围


try...after 不管try中执行情况如何,after都会执行,这个机制通常用于资源释放
{ok, Fd} = file:open("test.txt", [read]),
try
    do_something_with_file(Fd)
after
    file:close(Fd)
end

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics