【问题标题】:erlang phylosophy: Should I let users deal with wrong input or not?erlang 哲学:我应该让用户处理错误的输入吗?
【发布时间】:2012-04-29 23:58:19
【问题描述】:

是这样的:

% print/1: Prints out the integers between 1 and N
print(0) ->   io:format("~w~n", [0]);
print(N) when is_integer(N) -> 
          io:format("~w~n", [N]),
          print(N - 1).

如果用户输入一个非整数,就会发生这种情况:

11> effects:print('alfalfa').
** exception error: no function clause matching effects:print(alfalfa)

关于哲学:我应该以这种方式更正我的程序,以便“捕获”所有类型的输入吗?

% print/1: Prints out the integers between 1 and N
print(0) ->   io:format("~w~n", [0]);
print(N) when is_integer(N) -> 
          io:format("~w~n", [N]),
          print(N - 1).
% Last Line added:
print(_Other) -> false.

我是 erlang 的新手。是否有一些约定来处理这个问题?

谢谢!

【问题讨论】:

    标签: erlang


    【解决方案1】:

    在 Erlang 中,大多数情况下你不会发现这些糟糕的 API 用法。如果没有模式匹配调用,则会抛出带有相当冗长消息的exception of class exit ({function_clause, CallStack})。 几乎每个标准库方法都会抛出。目前我想不出反例。

    顺便说一句:如果出现某种错误(主要不是使用错误),您通常会返回 {error, Msg},而不是 false。在好的情况下,ok{ok, Datum} 会被返回。

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 2011-10-15
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 2011-12-01
      相关资源
      最近更新 更多