[英]Java unreported Exception error
我有一個方法,它將兩個向量加在一起,如果這些向量的長度不同,我需要返回一個異常。 我寫了一段代碼
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和catch相關,但我不知道如何修復它。 我該怎么辦?
每當你做一些可以拋出特定類型的Exception
東西時,你必須有適當的東西來處理它。 這可以是兩件事之一:
try
/ catch
塊包圍它; 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);
}
這將允許您在發生時處理它。 如果一切都出錯,它可以讓你返回一些特定的結果,或者(在這種情況下)打印錯誤並終止程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.