java - 如何在具有接口(interface)返回类型的方法中实现错误处理

标签 java methods try-catch

我有一个将矩阵相加的方法。如果矩阵大小不同,我需要捕获错误。当我将 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/

相关文章:

java - 尝试通过 REST API 访问 Azure 数据湖存储 Gen 2 中的文件系统时出现 403 错误

java - 在java中显示线程的繁忙状态

c# - `Fault` try block 中的关键字

java - 不输入 Y/N 时返回错误

struct - ColdFusion 中 cfcatch 的类型

java - 知名类型的 android nfc intent-filter

包含数组方法的 JavaScript 函数未返回所需结果

java - main 中的方法不会调用对象实例的方法?

没有类的 Java 对象

当方法签名为 Map<String, IMyInterface> 且 MyClass 实现 IMyInterface 时,Java 将不接受 Map<String, MyClass> 参数