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

前端 未结 4 968
刺人心
刺人心 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.

提交回复
热议问题