if (cb1.isSelected()) {
String charteredTo = (t6.getText());
try {
CharterFlight cf = new CharterFlight(num, origin, destination, length, time, charteredTo);
schedule.addFlight(cf);
} catch (StringIndexOutOfBoundsException err) {
System.out.println("fuck");
}
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
t5.setText("");
t6.setText("");
} else {
int seats = Integer.parseInt(t7.getText());
try {
PassengerFlight pf = new PassengerFlight(num, origin, destination, length, time, seats);
schedule.addFlight(pf);
} catch (StringIndexOutOfBoundsException err) {
System.out.println("fuck");
}
我这段代码的目的是,代码根据用户在GUI输入的内容,创建对象失败的话,便运行CATCH里面的代码.系统输出确实是StringIndexOutOfBoundsException错误,但是CATCH里面的代码好像没有成功运行.为什么啊?
StringIndexOutOfBoundsException
先修改为Exception,输出下err看到底什么类型
String是可变字符串长度,也就是说是无限制长度,无论你放多少字符进去都不可能下标溢出,那么问题就来了,为什么你会在控制台看到红色代码呢?我想可能是抛出的是那个异常的的父类或子类,要不就是幻觉~
你通过控制台报错信息,看一看报错具体在哪个类里边,schedule.addFlight(cf);你catch的是这个方法,但是这个方法如果没有throws Exception,
那么你在这里是捕获不到异常的。你可以给addFlight()这个方法加上throws Exception,或者将try{}catch()放到这个方法内部,然后再试试。
首先你catch的异常类型,就不是你在控制台看到的异常类型,不是Catch括号内的异常类型,它为什么要catch呢?