在基类需要异常被捕获时在派生类构造函数中使用Super

时间:2013-02-26 17:11:51

标签: java exception constructor derived-class super

我正在尝试将类B派生到Java中的新类C中。基类构造函数要求必须抛出或捕获未报告的异常。但是如果我尝试将super(..)放在try / catch中,那么我被告知对super的调用必须是构造函数中的第一个语句。有没有人知道解决这个问题?

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)
         {
         }
     }
 }

非常感谢, 克里斯

4 个答案:

答案 0 :(得分:1)

您始终可以使用throws子句在构造函数签名中声明 Exception

public C(String s) throws WhatEverException
    {

答案 1 :(得分:1)

我所知道的唯一方法是在子类构造函数中抛出异常。

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

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

}

答案 2 :(得分:0)

如果没有在第一个语句中调用超级构造函数,则无法定义构造函数。如果可能你可以抛出运行时异常,那么你不需要编写try / catch块。

答案 3 :(得分:0)

你需要了解三件事。

  1. 在子构造函数中,super必须是第一个语句,
  2. 如果父类方法抛出异常,那么子类可以选择捕获它或将异常抛回父类。
  3. 您不能减少子类中的异常范围。
  4. 示例 -

    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();
    
    }
    
    }