我有一个将矩阵相加的方法。如果矩阵大小不同,我需要捕获错误。当我将 try 和 catch 添加到我的方法中时,我在线程“main”java.lang.Error 中收到异常: Unresolved 编译问题: 该方法必须返回 Matrix 类型的结果
接口(interface)中的矩阵,部分赋值我无法更改返回类型。那么如何处理错误并保持返回类型正确呢?
public Matrix plus(Matrix other) throws RuntimeException{
try {
int[][] newMatrix = this.cloneMatrix();
int[][]mMatrix = castFromMatrix(other);
for (int y = 0; y < mMatrix.length; y++) {
for (int x = 0; x < mMatrix[0].length; x++) {
newMatrix[y][x] = newMatrix[y][x] + mMatrix[y][x];
}
}
Matrix sumMatrix = new EverhartMatrix(newMatrix);
return sumMatrix;
}
catch (Exception e) {
System.out.println("Plus method can not be employeed on matrices of different sizes");}
}
最佳答案
您面临的问题是因为您声明您的方法返回 Matrix
对象,并且在 catch 部分中您没有返回任何内容,这就是为什么编译器说此方法必须返回 Matrix 类型的结果,您只需添加 return null;
在您的System.out.println
之后调用这将解决您的问题,请记住返回 null 是一种不好的做法,因此可能需要将返回类型更改为 Optional<Matrix>
如果发生异常,则返回一个空的可选值。
关于java - 如何在具有接口(interface)返回类型的方法中实现错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62011189/