2015-10-19

Ruby : Exception bug??

......just code
require 'thread'

$temp = Thread.new do
  loop do
    puts 'loop me'
    begin
      puts "try thread"
      raise Exception.new('QwQ') if rand > 0.5
      puts "skip try"
    rescue
      puts "QwQ"
    end
    sleep(0.5)
  end
  puts '...WTF'
end

loop do
  puts "runner #{Thread.list.length} #{$temp.status}"
  sleep(2)
end
loop 會 fail loop ... 然後把所有的 rescue 改成 rescue Exception => e 就會成功,like
require 'thread'

$temp = Thread.new do
  loop do
    puts 'loop me'
    begin
      puts "try thread"
      raise Exception.new('QwQ') if rand > 0.5
      puts "skip try"
    rescue Exception => e
      puts "QwQ"
    end
    sleep(0.5)
  end
  puts '...WTF'
end

loop do
  puts "runner #{Thread.list.length} #{$temp.status}"
  sleep(2)
end
......兩個檔案diff只有一行......Orz"......成功... 原因: rescue 預設是 StandardError 而非 Exception ...... 來源: https://robots.thoughtbot.com/rescue-standarderror-not-exception

2 則留言:

  1. 怎麼不考慮改丟 StandardError.new 呢?

    回覆刪除
  2. ......因為來源是其他的gem搞出來的,或是C lib...這邊只是demo解決方式而已(來源curb我有上patch且對方接受了)

    回覆刪除