2011-11-07 37 views
4

這種情況:erlang phylosophy:我應該讓用戶處理錯誤的輸入嗎?

% 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。有處理這個問題的一些約定嗎?

謝謝!

回答

7

在Erlang中,你大多不會遇到如此糟糕的API用法。如果沒有模式匹配調用,則會引發exception of class exit帶有相當詳細的消息({function_clause, CallStack})。幾乎每個標準庫方法都會拋出。目前我沒有想到反例。

順便說一句:如果出現某種錯誤(主要是不使用錯誤),你大多會返回{error, Msg},而不是假。在好的情況下,ok{ok, Datum}將被退回。

+1

非常感謝! –