Java: Try/Catch Statements: While exception is caught, repeat try statements?

52,013

Solution 1

Something like this ?

while(condition){

    try{

    } catch(Exception e) { // or your specific exception

    }

}

Solution 2

One way is to use a while loop and exit when the name has been set properly.

boolean success = false;
while (!success) {
    try {
        // do stuff
        success = true;
    } catch (IOException e) {

    }
}

Solution 3

There is no "re-try" in the language, like others suggested already: create an outer while loop and set a flag in the "catch" block that triggers the retry (and a clear the flag after a successful try)

Solution 4

Would it be ok to use external lib?

If so, check out Failsafe.

First, you define a RetryPolicy that expresses when retries should be performed:

RetryPolicy retryPolicy = new RetryPolicy()
  .retryOn(IOException.class)
  .withMaxRetries(5)
  .withMaxDuration(pollDurationSec, TimeUnit.SECONDS);

Then, you use your RetryPolicy to execute a Runnable or Callable with retries:

Failsafe.with(retryPolicy)
  .onRetry((r, f) -> fixScannerIssue())
  .run(() -> scannerStatement());

Solution 5

You can use https://github.com/bnsd55/RetryCatch

Example:

RetryCatch retryCatchSyncRunnable = new RetryCatch();
        retryCatchSyncRunnable
                // For infinite retry times, just remove this row
                .retryCount(3)
                // For retrying on all exceptions, just remove this row
                .retryOn(ArithmeticException.class, IndexOutOfBoundsException.class)
                .onSuccess(() -> System.out.println("Success, There is no result because this is a runnable."))
                .onRetry((retryCount, e) -> System.out.println("Retry count: " + retryCount + ", Exception message: " + e.getMessage()))
                .onFailure(e -> System.out.println("Failure: Exception message: " + e.getMessage()))
                .run(new ExampleRunnable());

Instead of new ExampleRunnable() you can pass your own anonymous function.

Share:
52,013
Admin
Author by

Admin

Updated on July 17, 2022

Comments

  • Admin
    Admin almost 2 years

    Is there any way to do this?

    //Example function taking in first and last name and returning the last name.
    public void lastNameGenerator() throws Exception{
        try {
            String fullName = JOptionPane.showInputDialog("Enter your full name");
            String lastName = fullName.split("\\s+")[1];
        catch (IOException e) {
            System.out.println("Sorry, please enter your full name separated by a space.")
            //Repeat try statement. ie. Ask user for a new string?
        }
        System.out.println(lastName);
    

    I think I can use scanner for this instead, but I was just curious about if there was a way to repeat the try statement after catching an exception.

  • Rohit Jain
    Rohit Jain over 10 years
    This might result in StackOverflow if exception keeps on occurring. Just FYI.
  • Nir Alfasi
    Nir Alfasi over 10 years
    This is a really bad idea - a potential for an infinite loop that will result in stackoverflow... at least add a counter for the numbers of retries and bail out once you've reached that number!
  • Jayamohan
    Jayamohan over 10 years
    What is IOException doing in the snippet? I know OP has mentioned it mistakenly.
  • Aniket Thakur
    Aniket Thakur over 10 years
    Catching Runtime Exceptions is not a good programming practice.
  • Rohit Jain
    Rohit Jain over 10 years
    @AniketThakur. Where do you see RuntimeException?
  • Silviu Burcea
    Silviu Burcea over 10 years
    No need for success = false; in catch. If the try block doesn't succeed, it will still be false.
  • M K
    M K over 10 years
    Yes, I came back to remove it.
  • Axel
    Axel over 10 years
    @RohitJain RuntimeException extends Exception so catching Exception will also catch RuntimeException which is not a good programming practice.
  • Admin
    Admin over 10 years
    @MK Thanks, this did it! If I may ask a follow up question. If my try is successful, how can I access fullName once I'm outside the while loop? I don't want to redeclare it because the user would have to enter something again.
  • Jayamohan
    Jayamohan over 10 years
    You would get java.lang.ArrayIndexOutOfBoundsException: 1 for inputs like "test", "abc" etc..
  • Aniket Thakur
    Aniket Thakur over 10 years
    @sᴜʀᴇsʜᴀᴛᴛᴀ it is possible fullName to be null which may give NPE which is subclass of runtime exception.
  • Axel
    Axel over 10 years
    Yes, thank you, I forgot to remove the [1] when I copy/pasted the code.
  • Rohit Jain
    Rohit Jain over 10 years
    @Axel. Yeah true. That should have been the comment. Catching Exception is not a good idea.
  • Axel
    Axel over 10 years
    Yes, a bit more compact than my version. But you also should handle null return value of JOptionPane.showInputDialog() (I think it might be returned if the dialog is closed using the controls in the window decoration or by hitting ESC but the documentation is somewhat unclear in this regard).
  • M K
    M K over 10 years
    You can declare the variables outside while loop and initialize them to null or empty string. Until you get "success" the code will be stuck in the while loop. So, when you get out of the loop, you will have the variables set up with correct values.
  • Axel
    Axel over 10 years
    Depending on whether or not you believe in the "one-return-per-method" rule, you could even just return from within the loop and change it to while(true) { ... }. (In this example, not always of course.)
  • Aniket Thakur
    Aniket Thakur over 10 years
    Yeah a null check is needed before calling split() on fullName.
  • Axel
    Axel over 10 years
    @Aswin R I rejected your edit because it introduced an error. See my comment to Jayamohans solution.
  • Mohayemin
    Mohayemin over 10 years
    @sᴜʀᴇsʜᴀᴛᴛᴀ: OP was catching IOException. You could catch that too.