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 to me ?
The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
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.
To understand this let's consider an example where we have a class
Mammal
which definesreadAndGet
method which is reading some file, doing some operation on it and returning an instance of classMammal
.Class
Human
extends classMammal
and overridesreadAndGet
method to return the instance ofHuman
instead of the instance ofMammal
.To call
readAndGet
we will need to handleIOException
because its a checked exception and mammal'sreadAndMethod
is throwing it.And we know that for compiler
mammal.readAndGet()
is getting called from the object of classMammal
but at, runtime JVM will resolvemammal.readAndGet()
method call to a call from classHuman
becausemammal
is holdingnew Human()
.Method
readAndMethod
fromMammal
is throwingIOException
and because it is a checked exception compiler will force us to catch it whenever we callreadAndGet
onmammal
Now suppose
readAndGet
inHuman
is throwing any other checked exception e.g. Exception and we knowreadAndGet
will get called from the instance ofHuman
becausemammal
is holdingnew Human()
.Because for compiler the method is getting called from
Mammal
, so the compiler will force us to handle onlyIOException
but at runtime we know method will be throwingException
exception which is not getting handled and our code will break if the method throws the exception.That's why it is prevented at the compiler level itself and we are not allowed to throw any new or broader checked exception because it will not be handled by JVM at the end.
There are other rules as well which we need to follow while overriding the methods and you can read more on Why We Should Follow Method Overriding Rules to know the reasons.