【发布时间】: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)。
-
@MarsAtomic stackoverflow.com/questions/2416316/…
-
@m0skit0 好点。在编写代码时,我正在考虑临时解决这个问题的方法,但现在展示良好的形式永远不会太早。
标签: java exception compiler-errors