StillLearningToCode
StillLearningToCode

Reputation: 2461

looping over a try/catch block?

I am trying to write a try catch block like the following, but put it inside a loop. My issue is that when i put it in a while loop, it runs x amount of times. i want it to stop when the first try is successful. but give the option to run 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();
}

Upvotes: 4

Views: 2342

Answers (3)

Prince
Prince

Reputation: 20862

I hope I understood your problem correctly. Here's a 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++;
    }

Upvotes: 0

nhgrif
nhgrif

Reputation: 62052

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; within a try catch block and it will exit the loop that it's in (not just the try catch block), but from a readability stand point, this posted code might be better.

finished = true should be the final line of the try block. It won't throw an exception. And it will only execute if every other line of the try block executed without an exception. So if you get to finished = true, you didn't throw and exception, so you can toggle your flag and exit the loop.

Otherwise, if an exception is thrown, the finished = true; line won't execute. You'll deal with the exception, then increment the someCounter++ variable.

This is ideal from a readability standpoint because all possible while loop exits are marked in the conditional part of the while loop. The loop will continue until either someCounter is too large, or finished returns true. So if I'm reading your code, all I have to do is look through your loop for the parts where these variables are modified, and I can quickly understand the loop logic, even if I don't yet understand everything the loop is doing. I don't have to hunt for break; statements.

Upvotes: 1

SobiborTreblinka
SobiborTreblinka

Reputation: 575

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 )
    {

    }
}

Upvotes: 2

Related Questions