我们可以将"返回"替换为"抛出新的异常"吗?



我正在尝试编写一个用于分解的矩阵计算器。但是,在矩阵计算器中,在某些情况下,我不希望系统返回任何内容,而只是打印出错误消息。

我试图通过用抛出新的 Exception 方法替换返回调用来做到这一点,但它显然似乎不起作用,因为:1. 需要实现某种捕获/抛出和 2. 仍然需要一个 return 语句。

public double[][] multiply(Matrix other) {
  if(getCols() == other.getRows()) {
     double[][] mult = new double[getRows()][other.getCols()];
     for(int r = 0; r < mult.length; r++) {
        for(int c = 0; c < mult[0].length; c++) {
           mult[r][c] = mult(m1[r],findCol(other,c));
        }
     }
     return mult;
  }
  else {
     throw new MatrixException("Multiply");     
  }
}

因此,从else语句可以看出,代替return语句,将其替换为throw new MatrixException("Multiply")。这只返回一个 String 语句,但代码不会编译。有没有办法使用 try - catch 方法来抛出异常而无需实现返回?另外,是的,这是我第一次问问题,所以我仍然不完全熟悉问题格式化技术。

你可以通知调用方multiply可以通过像这样更改方法引发异常:

public double[][] multiply(Matrix other) throws MatrixException {}

所以现在的方法是:

public double[][] multiply(Matrix other) throws MatrixException {  // tells the method throws an exception
    if(getCols() == other.getRows()) {
        // ...
        return <your_valid_return_here>
    }
    throw new MatrixException("Multiply");  // inform the caller there is an exception if the previous condition is not met
}

此外,请记住MatrixException的异常类型(选中或未选中(才能遵循此方法。如果选中,调用方将被迫在调用代码中处理它(或报告其代码可能会引发异常(,如果未选中,则不会这样。

延伸阅读:

  • 何时选择选中和未选中的例外

最新更新