erlang phylosophy:我应该让用户处理错误的输入吗?

Her*_*nge 4 erlang

情况就是这样:

% 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).
Run Code Online (Sandbox Code Playgroud)

如果用户输入非整数,则会发生以下情况:

11> effects:print('alfalfa').
** exception error: no function clause matching effects:print(alfalfa)
Run Code Online (Sandbox Code Playgroud)

关于哲学:我应该以这种方式纠正我的程序,以便"捕获所有"的输入?

% 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.
Run Code Online (Sandbox Code Playgroud)

我是二郎的新手.是否有一些处理这个问题的惯例?

谢谢!

kay*_*kay 7

在Erlang中,你几乎不会遇到如此糟糕的API用法.如果没有模式匹配调用,则抛出带有相当详细消息的类exit的异常({function_clause, CallStack}).几乎所有标准库方法都会抛出.目前我没有想到反例.

顺便说一句:{error, Msg}如果出现某种错误(主要不是使用错误),你大多会回来,而不是假.在好的情况下ok{ok, Datum}将被退回.