If you must rescue Exception . . .

29
Oct/09
0

Sometimes you see Ruby code that rescue an exception at the top of the hierarchy:


rescue Exception => e

If you must do that, how about providing a means to control-C, by putting this in the method with the rescue:


trap("INT") do
  puts "Terminating . . . "
 return # or maybe exit
end
Filed under: Code, Ruby

Faster Net::HTTP for Ruby 1.8.6

20
Dec/08
1

We’ve been a bit frustrated at work with Net::HTTP performance (as have so many others) so here’s a monkeypatch for 1.8.6 that combines the buffer size increase in 1.8.7 with Aaron Patterson’s recent tweak to use non-blocking IO (unfortunately, the non-blocking IO patch doesn’t work with HTTPS, which is why we use the buffer size tweak when the @io variable suggests that HTTPS is happening. No guarantee implied, etc.


class Net::BufferedIO #:nodoc:

  alias :o ld_rbuf_fill :rbuf_fill

  def rbuf_fill

    BUFSIZE = 1024 * 16

    # HTTPS can't use the non-blocking strategy below in 1.8.6; so at least
    # increase buffer size over 1.8.6 default of 1024
    if !@io.respond_to? :read_nonblock
      timeout(@read_timeout) {
        @rbuf << @io.sysread(BUFSIZE)
      }
      return
    end

    # non-blocking
    begin
      @rbuf << @io.read_nonblock(BUFSIZE)
    rescue Errno::EWOULDBLOCK
      if IO.select([@io], nil, nil, @read_timeout)
        @rbuf << @io.read_nonblock(BUFSIZE)
      else
        raise Timeout::TimeoutError
      end
    end

  end

end
Filed under: Rails, Ruby

Teaching Ruby and Ruby on Rails again at Harvard

7
Aug/08
0

Once again, I’m pleased to be offering a course on Ruby and Ruby on Rails at Harvard: course; course site.

We’ll try to avoid this anti-pattern:

Ruby: eval, rescue, and Exception

7
Jun/08
0

Recently I needed to store bits of Ruby code in the database, and then evaluate them in the context of a particular instance. But one thing I flubbed up was the handling of exceptions. You see, in this situation, if you have bad Ruby code, you will likely raise an exception. My first attempt was, roughly, this code (wrong!):


begin
  eval s
rescue
  # log the fact that s couldn't be eval'ed
end

The catch is that when you use rescue without specify an exception, you are only catching StandardError or one of its subclasses. But eval will raise a SyntaxError (or worse), which is a subclass of ScriptError, which is not a subclass of StandardError. Therefore, you want to rescue an Exception that is further up the hierarchy. In short, better:


begin
  eval s
rescue Exception => e
  # log the fact that s couldn't be eval'ed
end

Nick Sieger provides a post with the Ruby Exception hierarchy, along with some code to generate it dynamically. Too bad this info isn’t in the on-line Pickaxe (http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html).

Filed under: Code, Ruby