while loop with exception handling

20,852

Solution 1

You should place the break; after the code is executed successfully.

do {
    try {
        Blob b = new Blob(id);
        break;
    }
    catch (Exception e) {
      System.out.println(e);
    }
    System.out.println("Enter a different ID: ");
    id = scan.nextInt();
} while(true);

So each time the loop would reach the end of its body, it would break out of the loop. You only should break after the blob is created successfully. Although I dont see why you put a break anyway. The while loop can check if the entered input was valid and simply stop the loop.

I modified the while in a do-while loop... By using true the loop will run forever, unless no exception is thrown by the constructor... This makes the code more generic (if you modify the conditions of the blob-construction, you don't have to modify the condition of the while loop).

Solution 2

Sorry, its kind of late to the party. Hope users who endup here may find this useful. The use of break keyword is discouraged Here is a very simple implementation to break away after implementing a retry mechanism This iterates over the loop for the specified number of times and also if the exception still persists, then the exception is thrown. This can be leveraged for an actual real world scenario where the resttemplate might actually result in IO/Network errors and can be retried in those cases

public class TestClass {

    public static void main(String[] args) throws Exception {

        try {
            int c = anotherM();
            System.out.println("Now the value is" + c);
        } catch (Exception e) {
            System.out.println("Inside" + e);
        }
    }

    public static int anotherM() throws Exception {
        int i = 4;
        Exception ex = null;
        while (i > 0) {
            try {
                System.out.println("print i" + i);

                throw new IOException();
                // return i;
            } catch (Exception e) {
                System.out.println(e);

                i--;
                if (i == 1) {
                    ex = new Exception("ttt");

                }

            }
        }
        if (ex != null) {
            throw new Exception("all new");
        } else {
            return i;
        }

    }

}
Share:
20,852
user2745043
Author by

user2745043

Updated on July 09, 2022

Comments

  • user2745043
    user2745043 almost 2 years

    This is my first time using exception handling so be gentle. I have a simple blob class that accepts an ID, the id must be between 30 and 50 or else an exception is thrown.

    public class Blob {
    int id;
    
    public Blob() {
    
    }
    
    public Blob(int id) throws Exception {
        this.id = id;
        if (id < 30 || id > 50)
            throw new Exception ("id = " +id+ ", must be between 30 and 50 inclusive");
    }
    }
    

    It should prompt the user to enter an id, and throw the exception if it's not between 30 and 50, and should continue until the user enters a valid input and then simply displays the id number.

    public class BlobCreator {
    
    public static void main(String[] args) {
        int id;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter ID number: ");
        id = scan.nextInt();
    
        do {
            try {
                Blob b = new Blob(id);
            }
    
            catch (Exception e) {
                System.out.println(e);
            }
            System.out.println("Enter a different ID: ");
            id = scan.nextInt();
        }
        while(true);
        }   
    System.out.println("Blob ID: " +id);
    }
    

    I think that I am using the throw and catch correctly, but my loop isn't working correctly so I think that should be a simple fix but I can't get it just right. Also is using a while loop like I have the best way for this situation or is there a better way to loop through throw and catch?

    Thanks for any and all help