Why can't overriding methods throw exceptions broader than the overridden method?

前端 未结 15 1581
梦谈多话
梦谈多话 2020-11-22 13:47

I was going through SCJP 6 book by Kathe sierra and came across this explanations of throwing exceptions in overridden method. I quite didn\'t get it. Can any one explain it

15条回答
  •  情书的邮戳
    2020-11-22 14:25

    Well java.lang.Exception extends java.lang.Throwable. java.io.FileNotFoundException extends java.lang.Exception. So if a method throws java.io.FileNotFoundException then in the override method you cannot throw anything higher up the hierarchy than FileNotFoundException e.g. you can't throw java.lang.Exception. You could throw a subclass of FileNotFoundException though. However you would be forced to handle the FileNotFoundException in the overriden method. Knock up some code and give it a try!

    The rules are there so you don't lose the original throws declaration by widening the specificity, as the polymorphism means you can invoke the overriden method on the superclass.

提交回复
热议问题