【问题标题】:Java unreported Exception errorJava未报告的异常错误
【发布时间】:2014-10-16 21:51:21
【问题描述】:

我有一个将两个向量相加的方法,如果这些向量的长度不同,我需要返回一个异常。 我写了一段代码

public static Vector  vectorAdd(Vector v1, Vector v2) throws IllegalOperandException{
    if(v1.getLength() == v2.getLength()) {
        double[] temp = new double[v1.getLength()];
        for(int i = 0; i < temp.length; i++) {
            temp[i] = v1.get(i) + v2.get(i);
        }
        Vector v3 = new Vector(temp);
        return v3;
    } else {
        throw new IllegalOperandException("Length of Vectors Differ");
    }
}

但是一旦我编译了我的主要方法

else if (userInput == 2) {
            System.out.println("Please enter a vector!");
            System.out.println("Separate vector components by "
                + "using a space.");
            Vector v1 = input.readVector();
            System.out.println();
            System.out.println("Please enter a vector!");
            System.out.println("Separate vector components by "
                + "using a space.");
            Vector v2 = input.readVector();
            System.out.println();
            System.out.println();
            System.out.println(LinearAlgebra.VectorAdd(v1, v2));

有一个错误

错误:未报告的异常 IllegalOperandException;必须被抓住或宣布被扔掉 System.out.println(LinearAlgebra.vectorAdd(v1, v2));

我已经在谷歌上搜索了一个小时,但我不明白问题出在哪里。 我很确定这与 try and catch 相关,但我不知道如何解决它。 我该怎么办?

【问题讨论】:

  • 你抛出异常IllegalOperandException.so你需要处理异常
  • 尝试使用专门处理 IllegalOperandException 或一般处理异常的 try/catch 块围绕 System.out.println(LinearAlgebra blah blah)。
  • 这可能有用:What are checked exceptions?
  • @m0skit0 好点。在编写代码时,我正在考虑临时解决这个问题的方法,但现在展示良好的形式永远不会太早。

标签: java exception compiler-errors


【解决方案1】:

每当你做一些可以抛出特定类型的Exception 的事情时,你必须有一些东西来处理它。这可以是以下两种情况之一:

  1. try/catch 块包围它;
  2. Exception 类型添加到方法的throws 子句中。

在您的情况下,您正在调用 LinearAlgebra.vectorAdd() 方法,并且该方法可以抛出 IllegalOperandException (大概如果它的参数之一是狡猾的)。这意味着您调用它的方法也可以抛出该异常。要么抓住它,要么将throws IllegalOperandException 添加到出现该行的方法的签名中。听起来好像是你的 main 方法,所以它会变成

public static void main(String[] args) throws IllegalOperandException {
    //...
}

这称为让异常向上传播

要捕获异常,您需要

try {
    System.out.println(LinearAlgebra.VectorAdd(v1, v2));
} catch (IllegalOperandException e) {
    // do something with the exception, for instance:
    e.printStackTrace();
    // maybe do something to log it to a file, or whatever...
    // or you might be able to recover gracefully...
    // or if there's just nothing you can do about it, then you might:
    System.exit(1);
}

这将允许你在它发生时处理它。它使您能够在一切都出错时返回一些特定的结果,或者(在这种情况下)打印错误并终止程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多