跳至內容

Erlang 程式設計/錯誤

來自華夏公益教科書,自由的教學叢書

我們可以用 throw 和 catch 來處理錯誤。在這個例子中,引數的值會導致錯誤,從而丟擲異常。函式 g() 只有在引數大於 12 時才會正常工作。如果引數小於 13,則會丟擲異常。我們嘗試在 start() 中呼叫 g()。如果我們遇到問題,則會在 start() 中的“case catch”結構中捕獲異常。

示例程式列表

-module(catch_it).
-compile(export_all).
                                                                 %
% An example of throw and catch
                                                                 %
g(X) when X >= 13 ->
   ok;
g(X) when X < 13 ->
   throw({exception1, bad_number}).
                                                                 %
% Throw in g/1 
% Catch in start/1
                                                                 %
start(Input) ->
   case catch g(Input) of
       {exception1, Why} ->
          io:format("trouble is ~w ", [ Why ]);
       NormalReturnValue ->
          io:format("good input ~w ", [ NormalReturnValue ] )
   end.
                                                                 %
%============================================================== >%   
% sample output:
                                                                 %
8> c(catch_it).    
{ok,catch_it}
                                                                 %
9> catch_it:start(12).
trouble is bad_number ok
                                                                 %
10> catch_it:start(13).
good input ok ok
華夏公益教科書