【问题标题】:Using Super in a Derived Class Constructor When Base Class Requires Exceptions to be Caught当基类需要捕获异常时,在派生类构造函数中使用 Super
【发布时间】:2013-02-12 06:13:32
【问题描述】:

我正在尝试将 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)
         {
         }
     }
 }

非常感谢, 克里斯

【问题讨论】:

  • public C(String s) throws Exception ?
  • 是的,您坚持别人的错误决定,即从构造函数中抛出已检查异常。您还将使用已检查的异常定义您的构造函数。
  • 如果你想一想,你能做些什么来从异常中恢复?当构造函数抛出异常时,不会创建对象。

标签: java exception constructor derived-class super


【解决方案1】:

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

public C(String s) throws WhatEverException
    {

【讨论】:

    【解决方案2】:

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

    public class B {
        public B(String s) throws E {
           // ... your code .../
        }
    }
    
    public class C extends B {
       public C(String s) throws E { 
           super(s);
       }
    

    }

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        嗯,你需要了解三件事。

        1. 在子构造函数中super必须是第一条语句,
        2. 如果父类方法抛出异常,则子类可以选择捕获它或将异常抛回父类。
        3. 您不能缩小子类中异常的范围。

        示例 -

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

        【讨论】:

          猜你喜欢
          • 2017-12-18
          • 1970-01-01
          • 2011-11-13
          • 1970-01-01
          • 2021-11-11
          • 2016-07-19
          • 2015-07-18
          • 2018-07-21
          • 2015-08-18
          相关资源
          最近更新 更多