当其他模式也存在时,如何对简单的抛出进行模式匹配?

Posted

技术标签:

【中文标题】当其他模式也存在时,如何对简单的抛出进行模式匹配?【英文标题】:How to pattern match a simple throw when other patterns are present too? 【发布时间】:2019-12-05 21:08:45 【问题描述】:

我正在学习 erlang,但我不明白当你同时拥有 errorexit 时,你如何在 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 模式还是没有?当还有其他退出/错误模式时,我该如何处理我的投掷?

【问题讨论】:

【参考方案1】:

抛出是在错误模式、退出模式还是没有?

它被 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.

在外壳中:

27> my:go(fun() -> throw(5) end).
throw,5

换句话说,try F() 仅捕获 F 内部发生的错误,而不是代码中其他地方发生的错误。如果 catch 从这里捕获错误:

  5-> throw(44)

那么你不必写try F(),你可以写F()

【讨论】:

以上是关于当其他模式也存在时,如何对简单的抛出进行模式匹配?的主要内容,如果未能解决你的问题,请参考以下文章

Java异常的抛出

java 异常

详解 Scala 模式匹配

十分钟学会Lua三:编程技巧之闭包与模式匹配

Lua中assert( )函数的使用

Java中异常的抛出方式