Unable to catch ruby โ€‹โ€‹exception

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 do not get a "catch" message, I see an error:

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

Why? How can I catch my exceptions without typing their salvation classes?

+4
source share
2 answers

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

 rescue Exception 

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

However, the best solution is to get custom exceptions from StandardError .

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

+12
source

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 understand that without specifying an exception class in the rescue statement.

+3
source

All Articles