简体   繁体   中英

if a method in parent class “throws Exception”, can we remove it in overridden method

If a method in parent class throws Exception , can we remove it in overridden method?

class Parent{  
  void msg()throws IOException {System.out.println("parent");}  
}  

class TestExceptionChild extends Parent{  
  void msg(){  
    System.out.println("TestExceptionChild");  //this is i want to ask
  }  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild();  
   p.msg();  
  }  
}  

Yes, it is allowed: a subclass can tell Java that it is not going to throw a certain exception, and Java will take it.

This is useful in situations when you do know the exact class at the point of invocation.

Consider the following setup:

class A {
    public void foo() throws Exception {}
}
class B extends A {
    public void foo() {}
}

You are allowed to do this in the context that does not catch Exception :

B b = new B();
b.foo();

Java sees that b is of type B whose method does not throw a checked exception, so the call to foo() is allowed.

However, this results in an error:

A a = new B();
a.foo();

unreported exception Exception; must be caught or declared to be thrown

Now Java must consider A.foo() 's signature for the invocation. The signature includes throws Exception part, so Java must verify that the checked exception is appropriately handled.

Yes. You can remove, but not add, checked exceptions from an overridden method signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM