From: Yohanes Santoso Date: 2007-11-08T06:57:42+09:00 Subject: Re: Rambling: try/catch Casimir P writes: > Just had an vague idea about generic java "try-catch" converted to ruby- > world I would like some feedback on. > > I'm building a "microscopic CMS" system to learn more ruby, and of course > it would be good to implement proper error catching system. Try-catch is > what java uses. > > Now the vague idea was to create one error catching function, and to > throw all things that might fail (say loading a file) "through" that > function. Passed as a code block? I am not sure, it keeps slipping from > me. :) > > What do you think? > > -- > Casimir Pohjanraito > Art Portfolio: http://csmr.dreamhosters.com The idea of passing around a signal handler is not new. It allows you to handle low-level condition in a high-level manner. Here is one, done à la SRFI-34. def with_exception_handler(k = nil) begin yield rescue Exception => e if k then if k.call(e) == :retry then retry end end end end limited_patience_handler = lambda { # can be called to handle exception three times. # after that it loses patience and just reraise things. i=[1,2,"last one"] lambda{|e| if not i.empty? puts "Got exception ##{i.shift}: #{e.inspect}" :retry else puts "I'm done covering for you. Reraising to my supervisor" raise e end}}.call with_exception_handler(limited_patience_handler) { puts "Raising" raise "Test exception" puts "Never reach here" } ****Output: Raising Got exception #1: # Raising Got exception #2: # Raising Got exception #last one: # Raising I'm done covering for you. Reraising to my supervisor /tmp/x.rb:24: Test exception (RuntimeError) from /tmp/x.rb:3:in `with_exception_handler' from /tmp/x.rb:22 YS