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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With