I am studying exception handling in java (mainly in inheritance)

just look at the 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 ..... cannot override m1 () method

Now, if I replaced RemoteException in the parent class with IOException and vice versa in the child class. Then it compiles.

Any other checked exception combinations do not work here, even if I use a checked exception, which is on the same level.

Now I am confused, why redefinition occurs only in one case, and not in other cases ??? I will be very grateful for your reply.

+2
source share
4 answers

, , .

RemoteException - IOException. , IOException, RemoteException.

. , , , .

+4

, . RemoteException IOException, class1 IOException class2 RemoteException, .

+2

" " . . , class2.m1 , , (, Throwable) (IOException RemoteException).

IOException FileNotFoundException, . :

 } catch( IOException e) { ... }

IOException, - , .

+1

( Java 5) , , .

This means that you can make them more specific in classes that inherit from the original method. This concept is also called restriction reduction because you make it more specific which types.

public class Foo {...}


public class SomeException extends Exception {...}


public class A{
    public Foo methodName() throws SomeException{...}
}


public class Bar extends Foo {...}


public class SomeSpecificException extends SomeException {...}


public class B extends A {
    public Bar methodName() throws SomeSpecificException {...}
}

So you can always “go down” to the Inheritance hierarchy.

// Doesn't compile    
public class B extends A {
    public Object methodName() throws Exception {...}
}

An attempt to expand restrictions does not work.

0
source

Source: https://habr.com/ru/post/1760499/


All Articles