Handling exceptions raised in a Ruby thread

前端 未结 4 1617
陌清茗
陌清茗 2020-12-09 14:49

I am looking for a solution of classic problem of exception handling. Consider following piece of code:

def foo(n)
  puts \" for #{n}\"
  sleep n
  raise \"a         


        
4条回答
  •  清歌不尽
    2020-12-09 15:28

    Postponed exceptions processing (Inspired by @Jason Ling)

    class SafeThread < Thread
    
      def initialize(*args, &block)
        super(*args) do
          begin
            block.call
          rescue Exception => e
            @exception = e
          end
        end
      end
    
      def join
        raise_postponed_exception
        super
        raise_postponed_exception
      end
    
      def raise_postponed_exception
        Thread.current.raise @exception if @exception
      end
    
    end
    
    
    puts :start
    
    begin
      thread = SafeThread.new do
        raise 'error from sub-thread'
      end
    
      puts 'do something heavy before joining other thread'
      sleep 1
    
      thread.join
    rescue Exception => e
      puts "Caught: #{e}"
    end
    
    puts 'proper end'
    

提交回复
热议问题