我提出了一种方法,目的是删除问题清单。方法测试包含问题、答案、问题数量、点数。而且效果很好。
我得到以下错误:
无法访问的语句:System.out.println(“test \”+ testsindice - 1.getNomTest());
以下是代码:
public static int supprimerTest(Test[] tests, int nbrTests) {
int longueurTests = tests.length;
int indice = 0;
int noTest = 1;
int saisieNoTest = 0;
String nomTest;
System.out.println("***DELETE A TEST***\n");
if (nbrTests > 0) {
boolean fin = true;
do{
System.out.print("Please enter a number of the question to be deleted");
try {
indice = Clavier.lireInt();
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;
}
}catch (Exception e) {
if (nbrTests < 1){
System.out.print("ERROR ! the number must be between 1 and " + nbrTests + "try again...");
}else {
System.out.println("ERROR ! the number must 1. ... Try again...");
}
}
}while (fin);
}else {
System.out.println("Il n'existe aucun test.");
System.out.print ("\nTPress <ENTRER> to continue ...");
Clavier.lireFinLigne();
}
return nbrTests;
}谢谢你的帮助。
发布于 2018-04-14 23:50:06
出现此错误的原因是,异常的作用类似于返回语句,在返回语句中,它将被最近的异常处理程序捕获。
既然你有:
throw new IndexOutOfBoundsException();该抛出下的任何代码都将永远无法到达,因为它会立即跳转到catch块。
我希望这是有意义的。:)
发布于 2018-04-14 23:50:35
当您抛出异常时,抛出下面的代码将不会被执行。抛出调用异常,该方法只能在catch/finally块中继续。无法到达throw new IndexOutOfBoundsException();后的行。也许您的代码应该如下所示:
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
}
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;发布于 2018-04-14 23:55:09
当您使用try语句时,如果检测到它,它会自动抛出异常。因此,只需取出抛出的异常行,那么您的代码就可以工作了。
https://stackoverflow.com/questions/49837170
复制相似问题