繁体   English   中英

更正语法以在Elixir中取消省略try

[英]Correct syntax to de-omit `try` in Elixir

我目前正在使用Elixir官方指南学习Elixir。 我正在研究错误处理部分,并且遇到了某些部分。

有时,您可能希望将函数的整个主体包装在try构造中,通常是为了确保以后可以执行某些代码。 在这种情况下,Elixir允许您省略try行:

iex> defmodule RunAfter do
...>   def without_even_trying do
...>     raise "oops"
...>   after
...>     IO.puts "cleaning up!"
...>   end
...> end
iex> RunAfter.without_even_trying
cleaning up!
** (RuntimeError) oops

我很好奇如果不省略try语法,正确的语法是什么。 到目前为止,我最好的猜测是,如下所示,但这似乎不是正确的方法。

iex> defmodule RunAfter do
...>   try do 
...>     def without_even_trying do
...>       raise "oops"
...>     end
...>   after
...>      IO.puts "cleaning up!"
...>   end
...> end

try do ... after ... end应该在def里面:

iex(1)> defmodule RunAfter do
...(1)>   def without_even_trying do
...(1)>     try do
...(1)>       raise "oops"
...(1)>     after
...(1)>       IO.puts "cleaning up!"
...(1)>     end
...(1)>   end
...(1)> end
iex(2)> RunAfter.without_even_trying
cleaning up!
** (RuntimeError) oops
    iex:4: RunAfter.without_even_trying/0

您的第二个代码也是有效的,但是它将拦截在编译时定义方法时抛出的错误:

iex(1)> defmodule RunAfter do
...(1)>   try do
...(1)>     def without_even_trying do
...(1)>       raise "oops"
...(1)>     end
...(1)>     raise "at compile time"
...(1)>   after
...(1)>      IO.puts "cleaning up!"
...(1)>   end
...(1)> end
cleaning up!
** (RuntimeError) at compile time
    iex:6: (module)
iex(1)> RunAfter.without_even_trying
** (UndefinedFunctionError) function RunAfter.without_even_trying/0 is undefined (module RunAfter is not available)
    RunAfter.without_even_trying()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM