Reputation: 1475
I would like the exceptions to be rescued, raised and rescued again using exception hierarchy syntax like the below snippet..
class InnerCustomError < StandardError
def initialize(msg = "inner")
super
end
end
class OuterCustomError < StandardError
def initialize(msg = "outer")
super
end
end
begin
raise InnerCustomError
rescue InnerCustomError
raise OuterCustomError
rescue OuterCustomError, StandardError => e
e.message
end
but this raises ==> OuterCustomError (outer)
why is this behaviour? Instead I would like it to be rescued ..
I understand nested begin end blocks like below is used to achieve the same,
begin
begin
raise InnerCustomError
rescue InnerCustomError
raise OuterCustomError
end
rescue OuterCustomError, StandardError => e
e.message
end
also I understand there are performance impacts with this idea but I would like to understand how is the former interpreted?
Upvotes: 1
Views: 279
Reputation: 230286
but this raises
OuterCustomError
. Why is this behaviour?
Because that's how this construct works. The first matching rescue
is selected as a handler for the exception and the result of this handling will be the result of the begin/rescue
. If the handler raises and you want to catch that new exception, you need to add another layer of begin/rescue, exactly like you show in the last snippet.
It is described in the documentation here.
Upvotes: 3