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

标签 java constructor

我是否需要在每个构造函数上放置 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/

相关文章:

javascript - "this"在构造函数中分配的函数中如何工作?

C++ 错误 : use of deleted function during constructor call of custom class

c++ - 覆盖另一种方法使用的父类(super class)回调函数[C++]

c++ - 最烦人的解析 : why doesn't `g( ( f() ) );` call `f` 's default constructor and pass the result to `g` 's ctor that takes a `f` ?

java - HBase-0.90.6 在 hbase-site xml 文件中的 Window 7 错误配置

Java - 当我尝试打印时线程池同步问题

c# - 选择构建服务器

java - Android:使用 TabHost 和 TabWidget 自定义选项卡的外观

java - Intent 服务使我的应用程序崩溃?

php - Symfony2 服务容器 - 将普通参数传递给服务构造函数