iex> raise ArgumentError, message: "the argument value is invalid"
** (ArgumentError) the argument value is invalid
在可能产生错误的地方, 我们可以用 try/rescue 和模式匹配来处理:
iex> try do
...> raise "Oh no!"
...> rescue
...> e in RuntimeError -> IO.puts("An error occurred: " <> e.message)
...> end
An error occurred: Oh no!
:ok
也可以在一个rescue中匹配多个错误:
try do
opts
|> Keyword.fetch!(:source_file)
|> File.read!()
rescue
e in KeyError -> IO.puts("missing :source_file option")
e in File.Error -> IO.puts("unable to read source file")
end
iex> try do
...> raise "Oh no!"
...> rescue
...> e in RuntimeError -> IO.puts("An error occurred: " <> e.message)
...> after
...> IO.puts "The end!"
...> end
An error occurred: Oh no!
The end!
:ok
最常见的用法是处理需要关闭的文件和连接:
{:ok, file} = File.open("example.json")
try do
# Do hazardous work
after
File.close(file)
end
iex> try do
...> for x <- 0..10 do
...> if x == 5, do: throw(x)
...> IO.puts(x)
...> end
...> catch
...> x -> "Caught: #{x}"
...> end
0
1
2
3
4
"Caught: 5"
像上面提到的, throw/catch 非常少见, 通常在 library 提供的 API 不够完善时来产生缺省的错误信息.