Looping over a try / catch block?

I am trying to write a catch try block as shown below, but put it in a loop. My problem is that when I put it in a while loop, it starts x times. I want him to stop when the first attempt is successful. but give the opportunity to work up to 3 times.

    try {

            myDisplayFile();

        } catch (FileNotFoundException e1) {
            System.out.println("could not connect to that file..");

            e1.printStackTrace();
        }

    public static void  myDisplayFile() throws FileNotFoundException{
    Scanner kin = new Scanner(System.in);
    System.out.print("Enter a file name to read from:\t");
    String aFile = kin.nextLine();

    kin.close();

    Scanner fileData = new Scanner(new File(aFile));
    System.out.println("The file " + aFile + " contains the following lines:");

    while (fileData.hasNext()){
        String line = fileData.next();
        System.out.println(line);
    }//end while
    fileData.close();
}
+4
source share
3 answers
int max_number_runs = 3;
boolean success = false;

for( int num_try = 0 ; !success && num_try < max_number_runs ; num_try++ )
{
    try
    {
        /* CODE HERE */
        success = true;
    }
    catch( Exception e )
    {

    }
}
+2
source
int someCounter = 0;
boolean finished = false;
while(someCounter < 3 && !finished) {
    try {
        //stuff that might throw exception
        finished = true;
    } catch (some exception) {
        //some exception handling
        someCounter++;
    }
}

You can break;in the block try catch, and it will exit the loop in which it is located (and not just the block try catch), but from the point of view of readability, this published code may be better.

finished = true try. . , try exception. , finished = true, , .

, , finished = true; . , someCounter++.

, while while. , someCounter, finished true. , , , , , , , , , break;.

+1

I hope I understood your problem correctly. Here is the way.

    int noOfTries = 0;
    boolean doneWithMyStuff = false;
    final int MAX_LOOP_VAL = 10;
    int noOfLoops = 0;

    while(noOfTries < 3 && noOfLoops < MAX_LOOP_VAL && !doneWithMyStuff) {

        try {

            // Do your stuff and check success

            doneWithMyStuff = true;
        }
        catch (Exception e) {

            noOfTries++;
            e.printStackTrace();
        }
        finally {

            // Close any open connections: file, etc.

        }
        noOfLoops++;
    }
0
source

All Articles