简体   繁体   中英

Cannot reach statement

I made a method which purpose is to delete list of questions. The method Test contains questions, answers, number of questions, points. And works fine.

I get the following error:

Unreachable statement on : System.out.println("The test \\"" + tests[indice - 1].getNomTest());

Here is the code:

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; 
}

Thank you for your help.

The reason you have that error is because exceptions act similar to a return statement where it'll get caught by the nearest Exception handler.

Since you have:

throw new IndexOutOfBoundsException();

Any code underneath that throw will never be reached because it immediately jumps to your catch block.

I hope that makes sense. :)

When you throw an exception, the code below the throw will be not executed. Throw invoke exception and the method can continue only in catch/finally block. Lines after throw new IndexOutOfBoundsException(); cannot be reached. Maybe your code should be following:

if (indice < 1 || indice > nbrTests){
     throw new IndexOutOfBoundsException();
}
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;

When you use try statement, it throws exceptions automatically if it is being detected. Therefore, simply take out the throw exception line, then your code should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM