tags:

views:

52

answers:

2
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?

+3  A: 

See this post for an explanation:

http://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.

Hugo Peixoto
+3  A: 

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.

Jacob
Reason for downvote? It answers the question, and provides a better solution based on ruby best practices?
Jacob
Downvode was not by me. Thanks for the answer
SMiX
@Jacon: There's currently one upvote and no downvotes. When I first read your answer, I briefly downvoted it, because it was advocating `rescue Exception`, but cancelled the downvote when I saw you mentioning that the custom exception should derive from `StandardError`.
Andrew Grimm
Ah, that clarifies it. It is worth noting that `rescue Exception` is bad practice, so I'll add that in.
Jacob