From: rj-cole Date: 2005-11-17T12:27:19+09:00 Subject: Ruby style question from a newby: exceptions Hi, Any hints on the best way to catch exceptions from the point of view of good style for the following? --- puts "Create connection..." imap = IMAP.new('sslmail.somewhere.com', 993, true) puts "Capabilities: cap = #{imap.capability().join(" ")}" puts "Authenticate..." logged_in = false begin imap.authenticate('CRAM-MD5', 'myname', 'secret') logged_in = true rescue Net::IMAP::NoResponseError => e puts " Failed, #{e}" end puts "Try Login..." if ! logged_in then begin imap.login('myname', 'secret') logged_in = true rescue puts " Failed, #{e}" end end --- What am I trying to do and what don't I like? Basically I want to try a sequence of things until one of them works --- first I want to use the authenticate method and if that fails to use the login method. Each of these methods indicates failure by raising an exception. I want to log each failure (because I'm experimenting with the library at this stage). In this example I want to log each failure and on failure I want to cacade to an alternative strategy. How could this code be better written so that it is easier to read and understand the flow of the code? Would it be possible to achieve something like the following? --- exceptions = until_success \ { imap.authenticate ... }, { imap.login ... } if exceptions.failed then puts "Unable to login: #{exceptions.join('\n')}" else puts "Login successfull. Record of unsuccessfull attempts: \n \ #{exceptions.join("\n ")}" end --- with a function until_success taking a sequence of blocks as arguments? regards, Richard.