From: Brian Candler Date: 2003-07-05T07:07:14+09:00 Subject: Re: The best way to catch errors On Sat, Jul 05, 2003 at 05:58:37AM +0900, Nigel Gilbert wrote: > My ruby program processes web pages, which it collects using the > methods in net/http. Every now and again, it tries to access a web > page which is no longer available, is protected with a password, is on > a slow server that yields a timeout, and so on. What I'd like to do, > therefore, is protect the page fetching method with a > begin...rescue..end construction that will cause the program simply to > move on to the next web page that needs to be fetched if there is an > access error. However, I don't want to trap any other kinds of error > (e.g. I'd still like to be able to interrupt the program with ^C). ^C does not generate an exception. Try it: begin loop do puts "hello" sleep 1 end rescue Exception => e print end # ^C gets you out of this program quite easily > Now, the obvious way of doing this is to append exception classes for > all the different types of web access error to the rescue clause, thus: > > rescue ProtocolError, ProtoSyntaxError, ..., TimeoutError => e > > where ... represents all the other possible errors. As far as I can > see, however, there are two problems with this. The first is that > ProtocolError (etc.) is defined in net/protocol.rb, which is 'required' > by 'net/http', which in turn is required by my program. The > consequence is that my program has no knowledge of ProtocolError and > the compiler objects that it is an uninitialized constant. Err...? If you do 'requre "net/http"' then the constant is available in your program, end of story. However you need to give the correct constant name, because it's defined in a different *module*: e.g. rescue Net::ProtocolError > The second > problem is that I don't know how to construct a complete list of all > the different types of exception that I should include in my rescue > clause. I've already discovered relevant exceptions defined in > http.rb, protocol.rb and timeout.rb, but there may be more. How can I > find a list of all the exceptions that could occur? That's down to the modules. But exceptions are organised in a hierarchy so usually you can find a sensible parent exception which catches all the things you want. Notice, for example, that all the exceptions in net/protocol.rb are subclasses of Net::ProtocolError, so a rescue on just that will catch all the more specific subclass errors as well. The higher-level exceptions RuntimeError or StandardError might also be appropriate for catching a wider range of exceptions. Regards, Brian.