我可以在Ruby中异常时访问绑定

时间:2011-10-04 11:21:11

标签: ruby exception

说我有:

begin
  2.times do
    a = 1
    1/0
  end

rescue
  puts $!
  debugger
end       

在此示例中,我想获得a的值。如果在a块中初始化begin,那么我可以在救援时访问它。但是,在此示例中,a是块本地的。当我解救时,有没有办法在异常时获得绑定?

2 个答案:

答案 0 :(得分:1)

你不能只在begin区块内放置另一个rescuedo块吗?

答案 1 :(得分:0)

似乎有可能做到这一点。但这不是很好:

class Foo < Exception
  attr_reader :call_binding

  def initialize
    # Find the calling location
    expected_file, expected_line = caller(1).first.split(':')[0,2]
    expected_line = expected_line.to_i
    return_count = 5  # If we see more than 5 returns, stop tracing

    # Start tracing until we see our caller.
    set_trace_func(proc do |event, file, line, id, binding, kls|
      if file == expected_file && line == expected_line
        # Found it: Save the binding and stop tracing
        @call_binding = binding
        set_trace_func(nil)
      end

      if event == :return
        # Seen too many returns, give up. :-(
        set_trace_func(nil) if (return_count -= 1) <= 0
      end
    end)
  end
end

class Hello
  def a
    x = 10
    y = 20
    raise Foo
  end
end
class World
  def b
    Hello.new.a
  end
end

begin World.new.b
rescue Foo => e
  b = e.call_binding
  puts eval("local_variables.collect {|l| [l, eval(l)]}", b).inspect
end

来源:How can I get source and variable values in ruby tracebacks?