我不知道如何成功尝试捕获异常。正如您所看到的,我已经启动了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) {
}
答案 0 :(得分:0)
将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)
...到无限远以及。
答案 1 :(得分:0)
必须捕获或声明抛出异常的函数。您的代码所遇到的问题位于setVehicleID(0);
行中,如您发布的错误日志中所述。
由于setVehicleID()
方法抛出异常,因此无论何时调用此函数,都必须捕获或重新抛出异常。要修复错误,您需要使用try catch:
tractorException()
{
try{
setVehicleID(0);
}
catch( tractorException e ) {
// Do something with error
}
}
答案 2 :(得分:0)
尝试输入此
你不能调用Directly setVehicleID方法,因为它有风险的方法
DT1 <- cbind(data.table(loc=c("L1","L2","L3"), product=c("P1","P2","P1")), matrix(10,nrow=3,ncol=12))
setkey(DT1, loc, product)
DT1
loc product V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12
1: L1 P1 10 10 10 10 10 10 10 10 10 10 10 10
2: L2 P2 10 10 10 10 10 10 10 10 10 10 10 10
3: L3 P1 10 10 10 10 10 10 10 10 10 10 10 10
DT2 <- cbind(data.table(loc=c("L2","L3"), product=c("P2","P1")), matrix(1:24,nrow=2,ncol=12))
setkey(DT2, loc, product)
loc product V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12
1: L2 P2 1 3 5 7 9 11 13 15 17 19 21 23
2: L3 P1 2 4 6 8 10 12 14 16 18 20 22 24