NetManiac

Witold Rugowski on web20 wave with Ruby on Rails

Catching general exceptions in Ruby

Posted on August 18, 2006 - Filed Under Ruby

I was wondering how to catch exceptions of any kind in Ruby. Well You just use begin rescue pair, without specifying what kind of exceptions do You want to catch. This perfectly gets all exceptions. But when You want to use some information, like exception name written to user, You have to declare some variable. But what type? Well simplest solutions are not always obvious, at least for me ;-)

Use Exception class which is parent for all exception instances… Ughh been stuck on such easy thing is a shame :)

begin
   # code
   # code
rescue Exception => msg
   puts "Something went wrong ("+msg+")"
end

Update

2008-01-10

There is much better way to do this, omit Exception in rescue and it will catch all exceptions

begin
   # code
   # code
rescue => msg
   puts "Something went wrong ("+msg+")"
end

Popularity: 9% [?]

Hits for this post: 11608

Similar Posts

Comments

7 Responses to “Catching general exceptions in Ruby”

  1. Harry Wood on June 6th, 2010 22:39

    That’s useful thanks

    You should probably fix the spelling of ‘rescue’ though :-)

  2. Witold Rugowski on June 7th, 2010 11:16

    Oh, indeed :) Fixed ;)

  3. asd on December 30th, 2010 2:40

    The spelling is still wrong lol

  4. Witold Rugowski on December 30th, 2010 22:31

    @asd
    Strange. Fixed it again (?)

  5. fault on February 4th, 2011 12:17

    According to wikipedia (I know…), the update isn’t correct:

    It is a common mistake to attempt to catch all exceptions with a simple rescue clause. To catch all exceptions one must write:
    begin
    # Do something
    rescue Exception
    # don’t write just rescue — that only catches StandardError, a subclass of Exception
    # Handle exception
    end

    http://en.wikipedia.org/wiki/Ruby_(programming_language)#Exceptions

    J.

  6. Witold Rugowski on February 9th, 2011 17:09

    Well, looks like You are right. But it is strange. I would swear I did tests before I wrote that. Anyway – rescue Exception => e is right way…

  7. capitale on October 5th, 2011 15:31

    the ruby way to interpolate strings like:
    “Something went wrong (“+msg+”)”
    is
    “Something went wrong (#{msg})”

Leave a Reply