我创建了3个类:品牌类(Marca)、商业品牌类(MarcaCommercial),它是品牌类的子类,如果品牌构造函数中启动的属性之一为null,则创建异常类(ExMarcaInvalida).我想在我的子类构造函数中捕捉这个异常,并声明它,如果捕捉到这个异常,则使用setter方法.然而,我不能这样做,因为除了第一行之外,我不能在任何地方初始化超类的值.有没有办法捕捉异常并做我想做的事情?下面留下所有3个类构造函数.

public Marca(String nome, String produtor, String regiao) 
        throws ExMarcaInvalida {
    this.nome = nome;
    this.produtor = produtor;
    this.regiao = regiao;
    if(nome.isEmpty() || nome.isBlank()){
        throw new ExMarcaInvalida("Nome invalido");
    }
}
public MarcaComercial(String rotulo, String email, 
    String num, String nome,String produtor, String regiao) 
    throws ExMarcaInvalida {
    try{
        super(nome, produtor, regiao); //ISSUE HERE
        this.rotulo = rotulo;
        this.email = email;
        this.num = num;
    }
    catch(ExMarcaInvalida e){
        setRotulo("Marca Branca");
        throw new ExMarcaInvalida("Marca Invalida");
    }
}

public class ExMarcaInvalida extends Exception{
    public ExMarcaInvalida(String msg){
        super(msg);
    }  
}

推荐答案

无法在子类的构造函数中引发异常

问题不是你不能排除例外.

真正的问题是你不能在构造函数的super调用中抛出异常...在构造函数本身中.super调用必须是构造函数的第一条语句,这意味着它不能在try ... catch中.

如果确实需要捕捉异常,则需要使用工厂方法来创建对象;例如

public MarcaComercial makeMarcaComercial(...) {
    try {
        return new MarcaComercial(...);
    } catch (ExMarcaInvalida ex) {
        // This will catch the exception whether it is thrown by 
        // the Marca constrictor or the MarcaComercial constructor
        //
        // Now we can throw a new exception or return a different object.
    }
}

但是,即使使用工厂方法,也无法"修复"并返回正在创建的原始对象.工厂方法无法访问该对象.

基本上,Java阻止您返回超类初始化失败的实例.这将是一个破碎的抽象,即使修复是有意义的.子类需要知道超类实现的私有细节.无论如何Java不允许这样做.


(实际上,我可以想出horrible种方法来颠覆这一点……但我不会描述它们,以防有人认为它们可能是个好主意.)

Java相关问答推荐

@ EnableRouting注释在Kotlin项目中不工作

当切换javaFX场景时,stage的大小正在Minimize

Javascript更新alert 可扩展内容样式与CSS—按钮更多/更少

Springdoc Whitelabel Error Page with Spring V3

屏蔽字母数字代码的Java正则表达式

CompleteableFuture是否运行在不同的内核上?

当返回Mono<;Something>;时,不会调用Mono<;void>;.flatMap

如何在Spring Java中从数据库列中获取JSON中的具体数据

在Eclipse中调试未导出的JDK模块的Java包

buildDir:File!&#的getter解决方案是什么?39.被抛弃

如何在Java中为thunk创建映射器函数

接受类及其接口的Java类型(矛盾)

Java类型推断:为什么要编译它?

无法在Java中获取ElastiCache的AWS CloudWatch指标

控制器建议异常处理

升级版本后出现非法访问错误

读取ConcurrentHashMap中的可变对象

带有提取器的JavaFXObservableList会根据侦听器的存在而改变行为

Vaadin Flow:设置密码显示按钮属性

有没有办法仅将 JComboBox 中的选定项目居中(因此保持组合框中的所有项目左对齐)