异常
try … catch
erlang中存在try…catch异常处理表达式,且这个表达式有值。
语法如下:
try FuncOrExpressionSequence of
Pattern1 [when Guard1] -> Expression1;
Pattern2 [when Guard2] -> Expression2;
catch
ExceptionType: ExPattern1 [when ExGuard1] -> ExExpressions1;
ExceptionType: ExPattern2 [when ExGuard2] -> ExExpressions2;
after
AfterExpressions
end
- 首先对FuncOrExpressionSql进行求值。
- 如果不产生异常,匹配模式Pattern1,Pattern2…,直到匹配成功。
2.1. 求值匹配成功的后面的表达式。
2.2. 表达式的值被当做try…catch值返回。 - 如果产生异常,匹配模式ExPattern1,ExPattern2…,直到匹配成功。
3.1. 求值匹配成功的后面的表达式
3.2. ExceptionType是原子thorw,exit,或error中的一个,未标明的话默认为throw. - 无论是否抛出异常,都要执行atfer关键字后的代码,在AfterExpressions中的返回值被自动舍弃。
捕获所有可能的异常
如果想捕获所有可能的错误,使用如下用法:
try Expr
catch
_:_ -> ... Code to handle all exceptions ...
end
栈跟踪
使用 erlang:get_stacktrace()来查看最近的栈跟踪信息。
注:不包含任何尾递归调用的路径信息。