gpt4 book ai didi

ruby - 为什么我们不能在 rescue 中访问局部变量?

转载 作者:数据小太阳 更新时间:2023-10-29 06:47:38 24 4
gpt4 key购买 nike

局部变量

begin
transaction #Code inside transaction
object = Class.new attributes
raise unless object.save!
end
rescue
puts object.error.full_messages # Why can't we use local varible inside rescue ?
end

实例变量

begin
transaction #Code inside transaction
@object = Class.new attributes
raise unless @object.save!
end
rescue
puts @object.error.full_messages # This is working fine.
end

最佳答案

您肯定可以在相应的 rescue block 中访问 begin 中定义的局部变量(当然假设在设置变量后引发了异常).

您不能做的是在 block 外访问 block 内定义的局部变量。这与异常无关。看这个简单的例子:

define transaction() yield end
transaction do
x = 42
end
puts x # This will cause an error because `x` is not defined here.

要解决此问题,您可以在 block 之前定义变量(您可以将其设置为 nil),然后将其设置在 block 内。

x = nil
transaction do
x = 42
end
puts x # Will print 42

因此,如果您像这样更改代码,它将起作用:

begin
object = nil
transaction do #Code inside transaction
object = Class.new attributes
raise unless object.save!
end
rescue
puts object.error.full_messages # Why can't we use local varible inside rescue ?
end

关于ruby - 为什么我们不能在 rescue 中访问局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4054621/

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