From: Joel VanderWerf Date: 2008-04-03T03:58:58+09:00 Subject: Re: Does Ruby support exception wrapping (exception chaining Brian Hartin wrote: > Joel, > > This doesn't really provide the main benefit to exception wrapping > mechanism: the ability to wrap low-level exceptions in an appropriate > higher-level exception and yet not lose the entire stack trace, or the > types and messages of the low-level exceptions. Exception wrapping > (a.k.a. chaining) in Java (a good model for this feature, I think) makes > the idea of a 'causal Exception' part of the class (via a 'cause' > field), and the stack trace: an Exception's stack trace includes the > causal 'chain' of Exceptions automatically. How about this? class ServiceNotFoundException < StandardError attr_reader :cause def initialize cause @cause = cause end end begin begin raise "foo" rescue Exception => e e2 = ServiceNotFoundException.new e raise e2, "The service could not be contacted: #{e.message}", e.backtrace end rescue Exception => e_outer puts e_outer p e_outer.cause puts e_outer.backtrace.join("\n ") end __END__ Output: The service could not be contacted: foo # wrapped-exceptions.rb:10 -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407