当其他模式也存在时,如何模式匹配一个简单的抛出?
How to pattern match a simple throw when other patterns are present too?
我正在学习 erlang,我不明白当你同时拥有 error
和 [=14] 时,你如何在 catch
块中的 throw
上进行模式匹配=]的?
模块
-module(err).
-compile([debug_info]).
-export([thro/1]).
thro(F)->
try F() of
3->"it worked gt then 3";
4->"gt then 4";
5-> throw(44)
catch
error:[Y|[Z|X]]->{Y+Z,2};
exit:[X|Y]->{exit,caught,"exiting with code:"++X};
error:44 -> {"thew on result"} % should it be 44 -> something
end.
用法:
对于第一种情况:err:thro(fun()->error([1,2,3])end).
对于第二种情况:err:thro(fun()->exit(["A","b"])end).
现在我想要这种情况:err:thro(fun()->5)end).
抛出的是 error
模式、exit
模式还是 none 模式?当还有其他退出/错误模式时,我该如何处理我的抛出?
Is a throw catched in an error pattern , a exit pattern or none ?
它陷入了 throw
模式,但是您的 throw()
必须在函数 F:
中
-module(my).
-compile([export_all]).
go(F)->
try F() of
_ -> no_errors
catch
error:[Y|[Z|_]]->{Y+Z,2};
exit:[X|_Y]->{exit,caught,"exiting with code:"++X};
throw:Value -> {throw, Value}
end.
在shell:
27> my:go(fun() -> throw(5) end).
{throw,5}
换句话说,try F()
只捕获 F 内部发生的错误,而不捕获代码中其他地方发生的错误。如果 catch 从这里捕获到错误:
5-> throw(44)
那你就不用写try F()
了,直接写F()
.
就可以了
我正在学习 erlang,我不明白当你同时拥有 error
和 [=14] 时,你如何在 catch
块中的 throw
上进行模式匹配=]的?
模块
-module(err).
-compile([debug_info]).
-export([thro/1]).
thro(F)->
try F() of
3->"it worked gt then 3";
4->"gt then 4";
5-> throw(44)
catch
error:[Y|[Z|X]]->{Y+Z,2};
exit:[X|Y]->{exit,caught,"exiting with code:"++X};
error:44 -> {"thew on result"} % should it be 44 -> something
end.
用法:
对于第一种情况:err:thro(fun()->error([1,2,3])end).
对于第二种情况:err:thro(fun()->exit(["A","b"])end).
现在我想要这种情况:err:thro(fun()->5)end).
抛出的是 error
模式、exit
模式还是 none 模式?当还有其他退出/错误模式时,我该如何处理我的抛出?
Is a throw catched in an error pattern , a exit pattern or none ?
它陷入了 throw
模式,但是您的 throw()
必须在函数 F:
-module(my).
-compile([export_all]).
go(F)->
try F() of
_ -> no_errors
catch
error:[Y|[Z|_]]->{Y+Z,2};
exit:[X|_Y]->{exit,caught,"exiting with code:"++X};
throw:Value -> {throw, Value}
end.
在shell:
27> my:go(fun() -> throw(5) end).
{throw,5}
换句话说,try F()
只捕获 F 内部发生的错误,而不捕获代码中其他地方发生的错误。如果 catch 从这里捕获到错误:
5-> throw(44)
那你就不用写try F()
了,直接写F()
.