如何在没有开始和结束块的情况下在 Ruby 中使用救援

发布于 2024-08-07 03:17:36 字数 147 浏览 7 评论 0原文

我知道有一个 begin的标准技术。救援<救援代码> end

如何单独使用 rescue 块?

它是如何工作的?它如何知道哪些代码正在被监视?

I know of the standard technique of having a begin <some code> rescue <rescue code> end

How does one just use the rescue block on its own?

How does it work, and how does it know which code is being monitored?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

仅冇旳回忆 2024-08-14 03:17:36

方法“def”可以充当“begin”语句:

def foo
  ...
rescue
  ...
end

A method "def" can serve as a "begin" statement:

def foo
  ...
rescue
  ...
end
那片花海 2024-08-14 03:17:36

您还可以内联救援:

1 + "str" rescue "EXCEPTION!"

将打印出“异常!”因为“字符串不能被强制转换为 Fixnum”

You can also rescue inline:

1 + "str" rescue "EXCEPTION!"

will print out "EXCEPTION!" since 'String can't be coerced into Fixnum'

素年丶 2024-08-14 03:17:36

我在 ActiveRecord 验证中经常使用 def/rescue 组合:

def create
   @person = Person.new(params[:person])
   @person.save!
   redirect_to @person
rescue ActiveRecord::RecordInvalid
   render :action => :new
end

我认为这是非常精简的代码!

I'm using the def / rescue combination a lot with ActiveRecord validations:

def create
   @person = Person.new(params[:person])
   @person.save!
   redirect_to @person
rescue ActiveRecord::RecordInvalid
   render :action => :new
end

I think this is very lean code!

从此见与不见 2024-08-14 03:17:36

示例:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end

此处,def 作为 begin 语句:

def
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end

Example:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end

Here, def as a begin statement:

def
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end
遗忘曾经 2024-08-14 03:17:36

奖金!您也可以使用其他类型的块来执行此操作。例如:

[1, 2, 3].each do |i|
  if i == 2
    raise
  else
    puts i
  end
rescue
  puts 'got an exception'
end

在 irb 中输出:

1
got an exception
3
 => [1, 2, 3]

Bonus! You can also do this with other sorts of blocks. E.g.:

[1, 2, 3].each do |i|
  if i == 2
    raise
  else
    puts i
  end
rescue
  puts 'got an exception'
end

Outputs this in irb:

1
got an exception
3
 => [1, 2, 3]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文