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

前端 未结 15 1578
梦谈多话
梦谈多话 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:37

    The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

    Example:

    class Super {
        public void throwCheckedExceptionMethod() throws IOException {
            FileReader r = new FileReader(new File("aFile.txt"));
            r.close();
        }
    }
    
    class Sub extends Super {    
        @Override
        public void throwCheckedExceptionMethod() throws FileNotFoundException {
            // FileNotFoundException extends IOException
            FileReader r = new FileReader(new File("afile.txt"));
            try {
                // close() method throws IOException (that is unhandled)
                r.close();
            } catch (IOException e) {
            }
        }
    }
    
    class Sub2 extends Sub {
        @Override
        public void throwCheckedExceptionMethod() {
            // Overriding method can throw no exception
        }
    }
    

提交回复
热议问题