[英]I have trouble using the try-catch method for a exception in java
我不知道如何成功嘗試捕獲異常。 如您所見,我已經開始了try-catch語句,但是不知道如何完成它。 我收到錯誤消息“ tractorException.java:83:錯誤:未報告的異常tractorException;必須被捕獲或聲明為setVehicleID(0);”
import java.io.*;
import java.util.*;
import javax.swing.*;
public class tractorException extends Exception {
protected int VehicleID;
public int setVehicleID(int VehicleID) throws tractorException {
if (VehicleID <= 0 || VehicleID > 100000) {
throw new tractorException();
} else {
this.VehicleID = VehicleID;
return this.VehicleID;
}
}
public int getVehicleID() {
return this.VehicleID;
}
tractorException() {
setVehicleID(0);
}
public static void main (String[] args) {
try {
throw new Exception("Something went wrong!!");
} catch (Exception e) {
}
將您的main
方法更改為:
public static void main (String[] args) {
try {
throw new tractorException(); // infinite loop ensues
} catch (Exception e) {
// this catch doesn't matter
}
}
之所以會發生無限循環,是因為tractorException
的構造函數調用setVehicleID(0)
,而后者又調用了throw new tractorException()
,正如您猜到的那樣, setVehicleID(0)
...調用到無窮遠甚至更遠。
引發異常的函數必須被捕獲或聲明為引發。 您的代碼存在的問題在setVehicleID(0);
行中setVehicleID(0);
如您發布的錯誤日志中所述。
由於setVehicleID()
方法會引發異常,因此setVehicleID()
調用此函數時,都必須捕獲或重新拋出該異常。 要解決您的錯誤,您需要在此調用周圍加入try catch:
tractorException()
{
try{
setVehicleID(0);
}
catch( tractorException e ) {
// Do something with error
}
}
嘗試輸入這個
您不能直接調用setVehicleID方法,因為它有風險
tractorException() {
try{
setVehicleID(0);
}catch(Exception e){
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.