Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not catch exception in ruby

Tags:

exception

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?

like image 978
Andrey Kuznetsov Avatar asked Dec 07 '22 01:12

Andrey Kuznetsov


2 Answers

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.

like image 58
Jacob Avatar answered Dec 31 '22 13:12

Jacob


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.

like image 23
Hugo Peixoto Avatar answered Dec 31 '22 12:12

Hugo Peixoto