Question

class A {
             public void process() { System.out.print("A,"); }
         }
public class B extends A
         {
             public void process() throws IOException  {   //LINE 23
             super.process();
             System.out.print("B,");
             throw new IOException();
          }

 public static void main(String[] args) {

 try { new B().process(); }

 catch (IOException e) { System.out.println("Exception"); }
 }
}

This question is from SCJP 6 , book says that compilation will fail due to an error at Line 23. But what i learned is , you can't throw broader exception when you overide method from parent class. In this Example my parent class method throws no exception , and my ovridden method throws IOException which is subclass of Exception. Then why its not working?

Moreover , i am considering that if my parent class method throws no exception , its by default considered as (( public void process() throws Exception. )) . Is that True??

Was it helpful?

Solution

Your understanding is not correct

public void process(){}

and

public void process() throws Exception{}

are not equivalent. what you can say is equivalent is:

public void process() throws RuntimeException{}

by definition you can not throw a broader exception from a overridden method in subclass. but you can always throw an unchecked exception from any method.

For better understanding please read

OTHER TIPS

Moreover , i am considering that if my parent class method throws no exception , its by default considered as (( public void process() throws Exception. )) . Is that True??

This isn't true. You must declare each checked exception thrown by a method whether it be in a class (concrete or abstract) or an interface.

However you can still throw unchecked exceptions and/or errors (ie, RuntimeException and subclasses, Error and subclasses) from a method not declaring to throw any exception (although you should really refrain from throwing Errors at all).

See the Java language specification, section 11.2 for more details. The beginning of this section reads (emphasis mine):

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method (§8.4.6) or constructor (§8.8.5) must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

yes You have to have a exception thrown by process method of class A

and exception must be border than exception of class B

this is mandatory because in case of polymorphism

if

A obj=new B();

now  

obj.process()

will not be forced to handle exception but method which is called actually throws exception

so in sub class overridden method can throw exception but of lower priority then parent class method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top