How to catch Exception Message in Erlang?

我的未来我决定 提交于 2019-12-06 11:46:17

Both the answers from @W55tKQbuRu28Q4xv and @Zed are correct but a little terse. :-)

There are two ways to locally catch an error: catchand try. Both will also catch non-local returns generated by throw.

catch is the older and simpler of the two and has the syntax catch Expr. If an error occurs in the expression being evaluated then catch returns {'EXIT',ErrorValue}, otherwise it just returns the value of the expression. One problem with it is that there is no way to see how the error return value has been generated so it can easily be faked in the expression. In the same way you can't see if the return value comes from a throw. N.B. this is not a bug but a feature. Also it is a prefix operator with a low priority so you would normally use it like:

R11 = (catch system_warning:self_test (....))

to avoid confusion. This was a mistake, it should have been catch ... end.

throw is more complex and allows you much greater control over over what to catch and how to handle both the normal returns and error/non-local returns. See the manual for a full description. @Zed's example shows the simplest case which catches everything.

> try                                        
>   R11 = system_warning:self_test("SysWarn")
> catch                                      
>   Ex:Type -> {Ex,Type,erlang:get_stacktrace()}                       
> end.

Try to use 'catch': R11 = catch system_warning:self_test (....)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!