2017-06-22 47 views
1

ruby​​中是否有可以處理異常的父類方法,以及如果使用子類時將首先處理錯誤的子類。第一個子類中的Ruby句柄錯誤

換句話說:

class Parent 
    def eat_apples(param) 
    puts "eat apples #{param}" 
    raise "pooey" 

    rescue => e 
    puts "parent error handler" 
    end 
end 


class Child < Parent 
    def eat_apples(param) 
    super(param) 

    rescue => e 
    puts "child error handler" 
    end 
end 

是它可以調用Child.new.eat_apples('something')並有父之後的子處理錯誤?

我非常希望做同樣的事情在父/子類,但功能不同的錯誤處置步驟

+1

不是沒有改變 - 整個'eat_apples'將運行,包括它的錯誤處理。 –

+0

不是true @DaveNewton,您可以在調用super方法之前執行擴展類錯誤處理。 –

+0

@BillyFerguson哪個......會是一個變化。 –

回答

2

爲什麼不乾脆重新定義,而無需調用超級方法?

class Child < Parent 
    def eat_apples(param) 
    puts "eat apples #{param}" 
    raise "pooey" 

    rescue => e 
    puts "child error handler" 
    end 
end 
+0

你知道彼得是怎麼回事。 –

1

這不是最好的例子,因爲我看不到你想要處理的那種用例。然而,據說你應該能夠在調用父方法之前先執行子錯誤處理,然後用super來處理子錯誤。

class Parent 
    def eat_apples(param) 
    puts "eat apples #{param}" 
    raise "pooey" 

    rescue => e 
    puts "parent error handler" 
    end 
end 


class Child < Parent 
    def eat_apples(param) 
    if param != "apple" 
     raise 
    end 
    super(param) 
    rescue => e 
    puts "child error handler" 
    end 


end 
0

創建提出了在父類異常的方法,並創建一個用於處理例外引發錯誤的另一種方法。現在在子類eat_apples方法中,調用引發異常的父方法並讓子處理異常。像下面一樣

class Parent 
    def eat_apples!(param) 
    puts "eat apples #{param}" 
    raise "pooey" 
    end 

    def eat_apples(param) 
    eat_apples!(param) 
    rescue => e 
    puts "parent error handler" 
    end 
end 


class Child < Parent 
    def eat_apples(param) 
    eat_apples!(param) 
    rescue => e 
    puts "child error handler" 
    end 
end 
1

將默認參數添加到方法和超級調用?這使您可以根據需要自由定製父和子例外,而無需放棄父例外,正如@Mark所建議的那樣。

class Parent 
    def eat_apples(param,throwitdown=false) 
    puts "eat apples #{param}" 
    raise "pooey" 

    rescue => e 
    raise e if throwitdown 
    puts "parent error handler" 
    end 
end 


class Child < Parent 
    def eat_apples(param) 
    super(param,true) 

    rescue => e 
    puts "child error handler" 
    end 
end 

puts Parent.new.eat_apples('from parent') 
puts Child.new.eat_apples('from child')