erlang 如何在函数上应用try和catch?

gg0vcinb  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(224)

我想知道是否可以在这个函数上应用一个try catch表达式:

add(X, Y) ->
    X + Y.

在这里,用户可以提供字符串而不是整数。
再举一个例子:

myfunction(X, Y) ->
    case X == Y of 
         true  -> X + Y;
         false -> X * Y
     end.

我举这些例子是想知道这是否可能,如何做到?

izj3ouym

izj3ouym1#

Yes, you can certainly use try-catch in those functions. Here what it would look like:

add(X,Y) ->
  try X + Y of
    Z ->
      Z
  catch
    error:badarith ->
      badargs
end.

If your concerned about values of other types being passed in, a better solution would be to add some guards to the function instead:

add(X,Y) when is_number(X), is_number(Y) ->
  X + Y.

This ensures that if the function body ( X + Y ) is only evaluated with numbers. If something other than a number is passed as either of these arguments the process will crash with a "no function clause matching" error. This is the Erlang way of ensuring the types are correct. While Erlang is dynamically typed, but you should generally know ahead of time if the values you have are suitable for the operation you are about to perform. That said, there are times you might not know the types if the variables you have, and in such cases wrapping the call in a case statement handles incorrect types:

case {X, Y} ->
  {X, Y} when is_number(X), is_number(Y) ->
    % safe to call add/2
    add(X, Y);
  _ ->
    % values aren't both numbers, so we can't add them
    nocanadd
end

The second function in your question myfunction/2 really should use guards too. Like this:

myfunction(X,Y) when is_number(X), is_number(Y) ->
  case X == Y of 
     true -> X + Y;
     false -> X * Y
  end.

相关问题