新手问题 关于 raise 没有被捕捉的问题

ailms · 2012年10月02日 · 最后由 woaigithub 回复于 2012年10月09日 · 2391 次阅读
def explode       
  raise "bam!" if rand(10) == 0 
end

def risky   

    10.times do    
      explode
    end
    begin
        puts "xxx"
    rescue Exception => f     (本来是期望这里能捕捉到的)
        puts f.class
    end

  "hello"   

end                

def defuse
    puts risky                   
end  

defuse

但实际执行时打出了整个 backtrace,说明没捕捉到

irb(main):024:0> defuse
RuntimeError: bam!
        from (irb):2:in `explode'
        from (irb):8:in `block in risky'
        from (irb):7:in `times'
        from (irb):7:in `risky'
        from (irb):21:in `defuse'
        from (irb):24
        from /home/bob/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'
irb(main):025:0> 
def risky   
  begin
    10.times do    
      explode
    end
    puts "xxx"
  rescue Exception => f 
    puts f.class
  end
end   

或者

def risky   
  10.times do    
    explode
  end
  puts "xxx"
rescue Exception => f 
  puts f.class
end   

谢谢!因为 the Ruby programming language 一书没有明确提到 rescue 的用法,是不是可以认为“raise 抛出的异常,只能被它 (raise) 所在 begin/end 中的 rescue 捕捉到,或者是整个 method 的 rescue 捕捉到”呢?

这还用明确说明么。。鱼在网里才能被你捕到啊!

@hooopo 这个比喻很恰当啊,哈哈...

多谢楼上热心的几位朋友.^_^

begin puts "xxx" 你的 begin 里面就 puts 一句,这一句不会出错的,所以不可能抛出什么异常。 异常是 explode 方法抛出来的,你的 begin 要包含这个方法的调用才可以的。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号