Andrey Kuznetsov
Andrey Kuznetsov

Reputation: 11840

Can not catch exception in ruby

class Collector
  class ContentNotFound < Exception
  end

  class DuplicateContent < Exception
  end
end

begin
  raise Collector::ContentNotFound.new
rescue
  puts "catch"
end

When I run the script I don't get "catch" message I see error:

lib/collector/exception.rb:10:in `<main>': Collector::ContentNotFound (Collector::ContentNotFound)

Why? How Can I catch my exceptions without typing their classes in rescue?

Upvotes: 4

Views: 1543

Answers (2)

Jacob
Jacob

Reputation: 23225

If you really want to catch those exceptions as-is, use:

rescue Exception

The bare rescue keyword only catches derivatives of StandardError (with good reason).

However, a better solution is to have your custom exceptions derive from StandardError.

For an explanation on why this is so, see this section of the PickAxe.

Upvotes: 12

Hugo Peixoto
Hugo Peixoto

Reputation: 3614

See this post for an explanation:

https://stackoverflow.com/questions/383229/common-programming-mistakes-for-ruby-developers-to-avoid/2019170#2019170

Basically, you can do

class ContentNotFound < RuntimeError
end

to catch that without having to specify an exception class in the rescue statement.

Upvotes: 3

Related Questions