I am learning the Exception handling in java (basically in inheritance)

前端 未结 4 954
刺人心
刺人心 2021-01-23 03:15

just look at program below..

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


        
相关标签:
4条回答
  • 2021-01-23 03:22

    "Same level" doesn't count. In inheritance, you can always only specialize things. So class2.m1 can throw anything which inherits from the original exception but it can't widen the exception (like throwing Throwable) or throw a completely different exception (IOException doesn't inherit from RemoteException).

    You could overload IOException with FileNotFoundException, for example. The reason is the catch:

     } catch( IOException e) { ... }
    

    This works for subtypes of IOException but would break for anything else which isn't what the developer would expect.

    0 讨论(0)
  • 2021-01-23 03:28

    You can throw a more specific exception in an overidden method, but not a less specific one. RemoteException is a subclass of IOException, so class1 can throw IOException and class2 RemoteException but not the other way round.

    0 讨论(0)
  • 2021-01-23 03:36

    Like with return types (since Java 5) Exceptions mentioned inside the method signature are covariant.

    This means you can make them more specific in classes that inherit the original method. This concept is also called narrowing of constraints because you make it more specific what the types are.

    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" the Inheritance hierarchy.

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

    Trying to widen the constraints doesn't work.

    0 讨论(0)
  • 2021-01-23 03:39

    When overriding a method that throws an Exception you can only throw the same Exception or a more specific subtype of that Exception.

    RemoteException is a subtype of IOException. Therefore when the parent method throws IOException your child method can throw RemoteException.

    You can also think it through logically. If a child method threw a broader Exception than the parent method, then the method might throw an Exception that doesn't match the parent.

    0 讨论(0)
提交回复
热议问题