Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java exception handling in inheritance

Tags:

java

just look at program below..

import java.io.*;
import java.rmi.*; 
class class1 
{
 public void m1() throws RemoteException 
{
 System.out.println("m1 in class1"); } }

 class class2 extends class1 
{
  public void m1() throws IOException 
{  
   System.out.println("m1 in class2");

} }

class ExceptionTest2 
 { 
public static void main(String args[])
 {
   class1 obj = new class1();
  try{ 
obj.m1(); 
} catch(RemoteException e){ System.out.println("ioexception"); }

} }

compile time error.....can not override m1() method

Now if I replace RemoteException in parent class with IOException and vice versa in child class. Then it is compiling.

Any other checked exception combinations are not working here, evenif I am using checked exception which are at same level.

Now I am confused why overriding is taking place only in one case, not in other cases??? I will realy appreciate your answer.

like image 762
user392675 Avatar asked Oct 16 '25 17:10

user392675


1 Answers

Exceptions rule in Inheritance goes like this:

"When a subclass overrides a method in super class then subclass method definition can only specify all or subset of exceptions classes in the throws clause of the parent class method(or overridden method)".

RemoteException inherits IOException, so RemoteException is a child class and IOEXception is a superclass. It means the subclass(class2) method that overrides parent class(class1) method, which throws IOException, can throw RemoteException but not vice-versa.

like image 52
Madhusudan Joshi Avatar answered Oct 18 '25 06:10

Madhusudan Joshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!