Ruby rescue custom exception

591 Views Asked by At

In following example:

class Foo
  class MyCustomerror < StandardError
    def message
      "My custom error"
    end
 end

 def self.do_standard
   1 / 0
 rescue StandardError => e
   puts e.message
 end

 def self.do_custom
   1 / 0
 rescue MyCustomerror => e
  puts e.message
 end
end

I have a problem with call rescue block which params is MyCustomerror. If i call Foo.do_standard, rescue block is called, however when i call Foo.do_custom rescue block with MyCustomerror isn't called. Where is the problem?

1

There are 1 best solutions below

5
Jörg W Mittag On

There is no place in your code that could raise a MyCustomError exception, so there is nothing to rescue from. The only exception that could possibly be raised by that code is a ZeroDivisionError.