簡體   English   中英

不能在子類的構造函數中拋出異常

[英]Can't throw exception in constructor of subclass

我創建了 3 個類:一個品牌類 (Marca)、一個作為品牌類的子類的商業品牌類 (MarcaComercial) 和一個異常類 (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不允許它。


(實際上,我可以想到幾種可怕的方法來顛覆這一點……但我不會描述它們,以防有人認為它們可能是個好主意。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM