EmptyStackException is an unchecked exception. And sice you are using a reference of type Toyota, so the method call will resolute to drive() in Toyota class. And since the drive method in Toyota class doesn't declare any checked exception in the throws clause, so you are not forced to catch any exception...
When you override a method in the subclass, you can loose the specification by omitting an exception. In this case, Toyota class can throw either no exception at all or EmptyStackException, which is an unchecked exception. Remember that Toyota.drive() method doesn't "inherit" the IOException thrown in the superclass's drive method.
Always remember that a Java method's signature ONLY include the method name and its parameter type list, contrary to many people's intuition, access modifier, return type and thrown exception do NOT belong to the signature and therefore are not guaranteed to be the same in the overriden methods.
jay vas wrote:Can somebody explain to me why my compiler is allowing me to NOT catch the clearly
relevant exception in the Toyota.drive() method ?
I have a different exception in that method.... but there is no reason why the compiler couldnt force me
to catch both exceptions, or at least catch the Exception superclass.
As mentioned by Ankit, it is just that drive function in Toyota class does not throw a checked exception so the compiler is not forcing you to put that in try catch block. If you use the same function with Car type of reference, the compiler would give you the compilation error (ie - Unhandled exception type IOException)
I hope this would clearify your confusion.
Message for you sir! I think it is a tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth