【问题标题】:Pass exception message to father class, without constructing the ,message with throw new exception();将异常消息传递给父类,而不用 throw new exception() 构造消息;
【发布时间】:2016-06-15 15:39:55
【问题描述】:

我有这个代码:

public class ExceptionFather extends Exception {}

public class ExceptionSon extends ExceptionFather {
    String someMessage;
    public ExceptionSon () {
        super(someMessage);
    }
}

我的目标是子异常会有自己的固定消息,会自动传递,而且每次抛出时我都不必在构造函数中写消息。

问题是这给了我一个语法错误,说我必须有一个构造函数来获取消息作为它的参数。

【问题讨论】:

  • 两个顶级公共类不应该在同一个文件中
  • 不是,是识别错误

标签: java exception inheritance constructor super


【解决方案1】:

您必须在 ExceptionFather 类中定义接受 String 参数的构造函数:

class ExceptionFather extends Exception {
    public ExceptionFather(String message) {
        super(message);
    }
}

之后,您将能够在子类ExceptionSon 中编写super(yourString)yourString 不能是子实例变量,因为在调用超类型构造函数之前无法访问它。但在这种情况下,您可以使用静态(类)变量或 String 文字:

class ExceptionSon extends ExceptionFather {
    private static String message = "message";
    public ExceptionSon() {
        super(message); // or just "message"
    }
}

【讨论】:

  • 谢谢,但这带来了另一个困难:现在当我抛出 ExceptionFather 类时,它要求输入字符串,因为它的构造函数需要一个字符串。
  • @Eyzuky,你需要定义一个不带参数的构造函数,因为当你声明另一个构造函数时,编译器不会放默认的构造函数(当没有构造函数时,编译器会放默认的)一个给你)
  • @Eyzuky,记住一个简单的规则——构造函数不会从父级继承给子级
猜你喜欢
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
  • 2015-09-21
  • 1970-01-01
  • 2019-11-07
相关资源
最近更新 更多