简体   繁体   中英

How to handle an exception thrown by superclass constructor in java?

I am getting an error is "Unhandled exception type Exception".So i have an question that how we can handle this thrown exception in our subclass.

class A 
{

  A() throws Exception 
  {
       System.out.println ("Executing class A constructor");
       throw new IOException();
  }
}

public class B extends A 
{
  B() //error
  {
       System.out.println ("Executing class B constructor");

  }

  public static void main ( String args[] )
  {
          try 
          {
          A a = new B();
          } 
          catch ( Exception e)
          {
                      System.out.println( e.getMessage() );
          }
  }
}

There is no way for the constructor of a subclass to handle an exception thrown by its superclass constructor.

The only thing you can do is to declare the subclass constructor as throwing the same (checked) exceptions as the super class constructor declares; eg

    B() throws Exception {
         System.out.println ("Executing class B constructor");
    }

That means that you cannot get the "Executing class B constructor" message to be printed if A() throws an exception.

If you think about it, this is a good thing. If you were able to catch the exception from super(...) in the subclass constructor, you would have to deal with an object that may not have been fully initialized. That is likely to be problematic.

Alternatively, if you do want to deal with the exceptions coming out of the superclass constructor, then hide the subclass constructor (ie make it private ) and instead use a factory method to create the subclass instances. That method can handle exceptions that emanate from the super or subclass constructor. But note that unless the constructor does something vile (eg smuggling this out via the exception), you still won't see the reference to the partially initialized / broken object.


I guess this is just an example, but it is worth pointing out that it is a bad idea to declare a method as throwing Exception (or Throwable ). You should declare the method as throwing the actual exceptions that are thrown.

You need to also throw exception in subclass.

 B() throws Exception
 {
   System.out.println ("Executing class B constructor");
 }

Add throws clause to B. B() throws Exception. Constructor B will expect that the exception to be handled as it is a child of A. Since it is a constructor you can not put it inside try catch. So the option is to throw it.

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