Exception Handling in Java - Inheritance
The other day somebody asked a question about exception handling in java. The question was this:
When we override a method in java which throws an exception, why is that we cannot change the exception that the parent class throws?
Well, I set to find out what are the possible scenarios that can occur when we throw different exceptions when overriding methods.
The first case I encounted was when I had a class BaseClass which had a method called testException() throws IOException. When I override this method from a class InheritedClass with a declaration like testException() throws ArrayIndexOutOfBoundsException, the compiler did not complain. I later realised that AIOOBE is a runtime exception so behavior was right.
The second case was when I declared the overriding method to throw an exception of type which happened to be a subclass of the parent exception class. So if I declare testException() throws FileNotFoundException, with the parent class method throwing IOException the compiler behavior was as I expected. Because the subclass can always be auto casted, it did not complain.
The third case was if we try the opposite of the second case. i.r BaseClass - testException() throws FileNotFoundException and the subclass InheritedClass declares, testException() throws IOException. As expected the compiler immedtiately complained of incompatibility between the declarations from the base class to the inherited class.
The fourth case was if I try and throw a totally unrelated exception in the overriding methods throws clause, like BaseClass testException() throws IOException and InheritedClass declares testException() throws SQLException, the compiler again complained of incompatibility.
Summing up:
Case 1: Overriding method throws runtime exception - Allowed
Case 2:Overriding method throws subclass of the exception type declared by the parent method - Allowed
Case 3: Overriding method throws base class of exception type declared by the parent method - NOT Allowed
Case 4: Overriding method throws totally unrelated compile time exception replacing parent method throws clause - NOT Allowed
Basically I realised that it really did not make sense for an overriding method to throw any other class of exception than what the method in the parent class threw. Java ofcourse allows you the possiblity to add exceptions in overriding methods.
1 comment:
Rajesh you done a great job. but you have not mentioned the case when the overriding method do not throws any exception instead the SuperClass methods was throwing.
In that case the code do not upsets the compiler and the code compiles fine...
Post a Comment