Getting to know ruby exceptions

January 18, 2010

Today i was reading the chapter 10 of my Programming Ruby book, about Ruby Exception Handling, Catch and Throw. Found some really interesting stuff, as usual, and i´m gonna write it all down here.

Exception Objects

Ruby lets you insert exception/error information into an object of class Exception (or its children). This object is passed to the preceding code, searching for a declaration that some code is capable of handling that exception. You can create your own Exception classes. To do this, all you need is to make your class children of StandardError or one of its children. It´s as simple as it gets:

class SomeVeryNastyError < StandardError
end

Error Handling

Things useful to know when dealing with error handling:

  • To cast an exception, just use the raise or Kernel.raise method. Arguments can be: raise [Exception class, [Message, [Callback array]]]
  • The code that is gonna have exception handling should be wrapped inside a begin/rescue/end block if it´s multilined or you can use rescue as a statement modifier for single-lines. The arguments to rescue clause are the exception classes it can handle (comma-separated) and an optional local variable to store a reference to the Exception object.
    begin
    # some code...
    rescue MyError, BadError, StandardError => err_reference
    #rescue stuff...
    end
    
  • Along with rescue, there are the else clause and the ensure clause:
    Code inside the else clause will execute if no exceptions happen;
    Code inside the ensure clause is always executed when the block terminates.

    begin
      # some code is executing and..
      raise SomeVeryNastyError, "Very nasty error occurred!"
    rescue SomeVeryNastyError => err_reference
      # here comes the rescue!
      puts "An error ocurred: #{err_reference.inspect}"
      # rescue code ...
    else
      puts "No error occurred!"
    ensure
      # having an error or not ...
      puts "execution ended!"
    end
    
  • There can be multiple rescue clauses within a block.
    begin
    #some code
    rescue ForcedError
    puts "Forced Error occurred!"
    rescue StandardError
    puts "Standard Error occurred!"
    end
    
  • A reference to the associated raised Exception object is placed into the global variable $!
  • Within a rescue clause, you can call the retry method, so that the code block begins its execution again.
  • You can add your own attributes and methods to your Exception classes.
    class MyError < StandardError
    attr_reader :ok_to_retry
    def initialize(retry)
    @ok_to_retry = retry
    end
    end
    begin
    #some code ...
    raise MyError(true)
    rescue MyError
    if $1.ok_to_retry
        puts "Retrying..."
        retry
      else
        puts "Not retrying!"
      end
    end
    

Catch and Throw

If you ever need to get a signal to terminate execution of some code, you will be in good hands when using catch and throw.

Firstly, you specify what to “catch”: it can be a Symbol or a String. A code block comes after and will be executed until it runs to the end or until the specified catch argument is thrown with the throw method. The throw method supports two arguments: a Symbol/String and a return value.

a = catch(:fire) do
  puts "Catching fire now!"
  throw(:fire,"fireee!")
end
puts a
# => fireee!

And that´s it for today! I´m heading towards chapter 11 of Programming Ruby tonight!
Feel free to post comments and examples in order to help me and the other fellas!

Other references: Programming RubySkorks post on exceptionsGoogle

About these ads

One Response to “Getting to know ruby exceptions”


  1. Fantastic goods from you, man. I have keep in mind your stuff prior to and you’re simply too wonderful. I really like what you’ve
    bought right here, certainly like what you are stating and the best way by which you say
    it. You make it entertaining and you continue to take care of
    to keep it smart. I can’t wait to learn much more from you. That is really a tremendous site.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: