I want exception as an instance of class Exception to be able to
re-raise it, not just a string.
You can do this:
#my_prog.rb
puts 'hello'
10/0
...
require 'open3'
begin
Open3.popen3("ruby my_prog.rb") do |stdin, stdout, stderr, wait_thr|
puts stdout.read
status_obj = wait_thr.value #Process::Status object returned.
puts status_obj.exitstatus
error = stderr.read
md = error.match(/\w+ Error/xm)
if md
e = Exception.const_get(md[0]).new if md
p e.class.ancestors
raise e
end
end
rescue ZeroDivisionError
puts 'Hey, someone divided by zero!'
end
--output:--
hello
1
[ZeroDivisionError, StandardError, Exception, Object, Kernel, BasicObject]
Hey, someone divided by zero!
Unfortunately, there are several exceptions whose names do not end in 'Error'--but you can modify the code to search for those specifically in the error message.