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.
1条答案
按热度按时间izj3ouym1#
Yes, you can certainly use try-catch in those functions. Here what it would look like:
If your concerned about values of other types being passed in, a better solution would be to add some guards to the function instead:
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:The second function in your question
myfunction/2
really should use guards too. Like this: