gpt4 book ai didi

elixir - 异常名称的模式匹配

转载 作者:行者123 更新时间:2023-12-02 09:24:39 26 4
gpt4 key购买 nike

我正在探索 Elixir 并且有疑问。假设我有这样的代码:

defmodule Drop2 do
def fall_velocity(planemo, distance) do
gravity = case planemo do
:earth -> 9.8
:moon -> 1.6
:mars -> 3.71
end
:math.sqrt(2 * gravity * distance)
end
end

我将一个负数传递为 distance使功能失败:
iex(8)> Drop2.fall_velocity(:earth, -20)
** (ArithmeticError) bad argument in arithmetic expression
(stdlib) :math.sqrt(-392.0)
drop2.ex:9: Drop2.fall_velocity/2

这可以通过添加异常处理来改善:
defmodule Drop2 do
def fall_velocity(planemo, distance) do
try do
gravity = case planemo do
:earth -> 9.8
:moon -> 1.6
:mars -> 3.71
end
:math.sqrt(2 * gravity * distance)
rescue
ArithmeticError -> {:error, "Distance must be non-negative number"}
CaseClauseError -> {:error, "Unknown planemo: #{planemo}"}
end
end
end

现在我们有:
iex(9)> Drop2.fall_velocity(:earth, -20)
{:error, "Distance must be non-negative number"}

很好,但我看不到模式 ArithmeticError火柴。在前面的示例中,生成的异常主要是文本, (ArithmeticError)括在括号中。这不是 Elixir 中常见的模式匹配。这是怎么回事?

最佳答案

In the previous example, the exception generated was mostly text, with (ArithmeticError) wrapped in parenthesis.


异常(exception)不是文本,只是 iex正在打印异常的文本表示,而不是确切的值 ( source)。这是确切的异常(exception):
iex(1)> try do
...(1)> :math.sqrt(-1)
...(1)> rescue
...(1)> e -> e
...(1)> end
%ArithmeticError{message: "bad argument in arithmetic expression"}
这是一个结构 ArithmeticErrormessage字段,如 Kernel.SpecialForms.try/1 的文档中所述:

Rescue clauses

Besides relying on pattern matching, rescue clauses provides some conveniences around exceptions that allows one to rescue an exception by its name.

关于elixir - 异常名称的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38865759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com