This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
| Generating and Understanding Tracebacks | ||
|---|---|---|
| Code | Expected | Actual |
def raise_exception
raise Exception, 'You wanted me to raise an exception, so...'
end
begin
raise_exception
rescue Exception => e
puts "Backtrace of the exception:\n #{e.backtrace.join("\n ")}"
end |
Backtrace of the exception: (irb):2:in `raise_exception' (irb):5:in `irb_binding' /usr/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding' :0 |
Backtrace of the exception: (irb):2:in `raise_exception' (irb):5:in `irb_binding' /usr/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding' /usr/lib/ruby/1.8/irb/workspace.rb:52 |
CALLER_RE = /(.*):([0-9]+)(:in \`(.*)')?/
def parse_caller(l)
l.collect do |c|
captures = CALLER_RE.match(c)
[captures[1], captures[2], captures[4]]
end
end
begin
raise_exception
rescue Exception => e
puts "Exception history:"
first = true
parse_caller(e.backtrace).each do |file, line, method|
puts %{ #{first ? "L" : "because l"}ine #{line} in "#{file}"} +
%{ called "#{method}" }
first = false
end
end |
Exception history: Line 2 in "(irb)" called "raise_exception" because line 24 in "(irb)" called "irb_binding" because line 52 in "/usr/lib/ruby/1.8/irb/workspace.rb" called "irb_binding" because line 0 in "" called "" |
Exception history: Line 2 in "(irb)" called "raise_exception" because line 17 in "(irb)" called "irb_binding" because line 52 in "/usr/lib/ruby/1.8/irb/workspace.rb" called "irb_binding" because line 52 in "/usr/lib/ruby/1.8/irb/workspace.rb" called "" |