gpt4 book ai didi

java - 我应该将抛出异常放在链式重载构造函数中的哪里?

转载 作者:行者123 更新时间:2023-12-01 18:06:04 24 4
gpt4 key购买 nike

我是否需要在每个构造函数上放置 throws 子句,或者只是将最终重载的构造函数传递给父类(super class)?

  //Constructors
public ManufacturedPart(){
this(0, null, 0, 0, 0);
}
public ManufacturedPart(int id){
this(id, null, 0, 0, 0);
}
public ManufacturedPart(int id, double lCost, double mCost){
this(id, null, 0, lCost, mCost);
}
public ManufacturedPart(int id, String desc, double sellPrice, double lCost, double mCost){
super(id, desc, sellPrice);
setLaborCost(lcost);
setMaterialCost(mCost);
}

//Set Labor Cost
public void setLaborCost(double lCost) throws InvalidProductionArgumentException {
if(lCost < 0)
throw(new InvalidProductionArgumentException("Labor cost can't be less than 0"));
else if(lCost >= 0)
laborCost = lCost;
}

//Set Material Cost
public void setMaterialCost(double mCost) throws InvalidProductionArgumentException {
if(mCost < 0)
throw(new InvalidProductionArgumentException("Material cost can't be less than 0"));
else if(mCost >= 0)
materialCost = mCost;
}

最佳答案

Do I need to place the throws clause on each constructor or just the final overloaded constructor being passed to the super class?

您需要将其放置在可能出现此异常的每个构造函数上。例如

public ManufacturedPart(int id) { // thrown not possible
this(id, null, 0, 0, 0);
}

public ManufacturedPart(int id, double lCost, double mCost)
throws InvalidProductionArgumentException { // it could happen here
this(id, null, 0, lCost, mCost);
}

如果异常是受检查的异常,您需要重构它,这样您就不必处理不可能发生的受检查的异常。

public ManufacturedPart(int id) { // thrown not possible
super(id, null, 0); // use super instead of a constructor which throws an exception
}

关于java - 我应该将抛出异常放在链式重载构造函数中的哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36350311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com