2

我有一个函数,当它的第一个参数是 atom 时,它会故意抛出throw

此代码的简化版本是:

-module(sample).

-export([main/1, throw_or_ok/1]).

main(_Args) ->
    throw_or_ok(throw).


throw_or_ok(Action) ->
    case Action of
        throw -> throw("throwing");
        ok -> ok
    end.

调用时出现透析器错误throw_or_ok

sample.erl:7: The call sample:throw_or_ok
         ('throw') will never return since it differs in the 1st argument from the success typing arguments:
         ('ok')

添加规格没有帮助,错误消息是相同的:

-module(sample).

-export([main/1, throw_or_ok/1]).

-spec main(_) -> no_return().
main(_Args) ->
    throw_or_ok(throw).

-spec throw_or_ok(throw) -> no_return(); (ok) -> ok.
throw_or_ok(Action) ->
    case Action of
        throw -> throw("throwing");
        ok -> ok
    end.

我怎样才能让 Dialyzer 接受throw_or_ok/1保证会抛出的调用?

4

2 回答 2

0

不幸的是,目前没有明确的方法可以通过规范将此标记为 Dialyzer 可接受的。

但是,也许您可​​以使用忽略警告注释。

于 2021-01-27T10:08:31.867 回答
0

看起来 if will putthrow它永远不会返回, if will putok模式永远不会匹配throw. 请参阅具有类似问题的主题。main/1需要改变的逻辑,例如:

main(Args) ->
    MaybeOk = case Args of
        0 -> throw;
        _ -> ok
    end,
    throw_or_ok(MaybeOk).

或者

main(_Args) ->
    throw_or_ok(_Args).
于 2021-01-27T19:20:36.347 回答