0

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?

Costy
  • 165
  • 2
  • 14
  • 1
    `rescue MyCustomerror` rescues `MyCustomerror` and its subclasses. But `ZeroDivisionError` isn't one of its subclasses. – Stefan Nov 16 '18 at 16:35

1 Answers1

2

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • It might be worth noting that `ZeroDivisionError` inherits from `StandardError` which is why `rescue StandardError` rescues it. – Stefan Nov 16 '18 at 16:45
  • Place or not place. It does not explain why in case call method do_standard is caught by StandardError, instead in case call do_custom not. – Costy Nov 16 '18 at 19:04
  • @Stefan In the above example MyCustomerror is also inherited by StandardError! – Costy Nov 16 '18 at 19:07
  • Both functions raise `ZeroDivisionError`. `ZeroDivisionError` is a `StandardError` so `.do_standard` rescues it. `ZeroDivisionError` is not a `MyCustomerror` and so `.do_custom` does not rescue it. – David Maze Nov 17 '18 at 02:41
  • @user3471671 it's the other way round: `MyCustomerror` inherits from `StandardError`. In the class hierarchy, `MyCustomerror` and `ZeroDivisionError` are siblings. – Stefan Nov 17 '18 at 13:57