4

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.

Thomas Lötzer
  • 24,832
  • 16
  • 69
  • 55
user392675
  • 69
  • 1
  • 1
  • 3
  • You have already posted this question http://stackoverflow.com/questions/3520596/i-am-learning-the-exception-handling-in-java-basically-in-inheritance – Jon Freedman Aug 19 '10 at 10:30

4 Answers4

5

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.

Madhusudan Joshi
  • 4,438
  • 3
  • 26
  • 42
2

RemoteException is more specific than IOException so you can declare that the member m1() of the inheriting class throws this. (RemoteException inherits from IOException and thus RemoteException is a special kind of IOException).

It does not work the other way round: by specifying that ANY object of type class1 throws a RemoteException in its member m1(), you can't specify that the same method in class2 throws something more generic (because class2 type objects are also class1 type objects).

Andre Holzner
  • 18,333
  • 6
  • 54
  • 63
1

A RemoteException is an IOEception, but not the other way around. Since class 2 extends class 1, all thrown exceptions must be compatible with the superclass exceptions. When class1.m1 throws an IOException, class2.m1 can throw a RemoteException since that is a specialization of an IOException.

Thomas Lötzer
  • 24,832
  • 16
  • 69
  • 55
0

Because two methods with the same signatures cannot throw different kinds of exceptions.

Pierre Gardin
  • 684
  • 1
  • 8
  • 23