Chris W
Chris W

Reputation: 145

Using Super in a Derived Class Constructor When Base Class Requires Exceptions to be Caught

I'm trying to derive a class B to a new class C in Java. The base class constructor requires that unreported exceptions must be thrown or caught. But if I try to put super(..) inside a try/catch then I'm told that the call to super must be the first statement in the constructor. Does anyone know a way around this?

public class C extends B
{
   //Following attempt at a constructor generates the error "Undeclared exception E; must be caught or declared
   //to be thrown
    public C(String s)
    { 
         super(s);
    }

    //But the below also fails because "Call to super must be the first statement in constructor"
    public C(String s)
    {
         try
         {
              super(s);
         }
          catch( Exception e)
         {
         }
     }
 }

Many thanks, Chris

Upvotes: 1

Views: 1992

Answers (4)

Dinesh Arora
Dinesh Arora

Reputation: 2255

Well there are three things that you need to understand.

  1. In a child constructor super must be the first statement,
  2. If a parent class method throws exception then the child class has the option to either catch it or throw the exception back to parent class.
  3. You cannot reduce the scope the exception in child class.

Example -

public class Parent {

public Parent(){
    throw new NullPointerException("I am throwing exception");
}

public void sayHifromParent(){
    System.out.println("Hi");
}
}


public class Child extends Parent{

public Child()throws NullPointerException{

    super();

}
public static void main(String[] args) {
    Child child = new Child();
    System.out.println("Hi");
    child.sayHifromParent();

}

}

Upvotes: 0

Arsen Alexanyan
Arsen Alexanyan

Reputation: 3141

You can't define constructor without calling super constructor in first statement. If it is possible You can throw runtime exception then You needn't to write try/catch blocks.

Upvotes: 0

RudolphEst
RudolphEst

Reputation: 1250

The only way I am aware of is to throw the exception in the subclass constructor too.

public class B {
    public B(String s) throws E {
       // ... your code .../
    }
}

public class C extends B {
   public C(String s) throws E { 
       super(s);
   }

}

Upvotes: 1

PermGenError
PermGenError

Reputation: 46408

You can always declare the Exception in constructor signature using throws clause.

public C(String s) throws WhatEverException
    {

Upvotes: 1

Related Questions