Reputation: 145
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
Reputation: 2255
Well there are three things that you need to understand.
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
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
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
Reputation: 46408
You can always declare the Exception
in constructor signature using throws clause.
public C(String s) throws WhatEverException
{
Upvotes: 1