加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 为什么我们不能在救援中访问局部变量?

发布时间:2020-12-16 19:27:44 所属栏目:百科 来源:网络整理
导读:局部变量 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 ins
局部变量
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

解决方法

您当然可以在相应的救援块中访问begin中定义的局部变量(当然,假设在设置变量之后引发了异常).

您不能做的是访问块外部块内定义的局部变量.这与例外无关.看这个简单的例子:

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

你可以做些什么来解决这个问题,就是在块之前定义变量(你可以将它设置为nil),然后在块内设置它.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读