Java: Try/Catch Statements: While exception is caught, repeat try statements?
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.
Admin
Updated on July 17, 2022Comments
-
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 over 10 yearsThis might result in StackOverflow if exception keeps on occurring. Just FYI.
-
Nir Alfasi over 10 yearsThis 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 over 10 yearsWhat is IOException doing in the snippet? I know OP has mentioned it mistakenly.
-
Aniket Thakur over 10 yearsCatching Runtime Exceptions is not a good programming practice.
-
Rohit Jain over 10 years@AniketThakur. Where do you see RuntimeException?
-
Silviu Burcea over 10 yearsNo need for success = false; in catch. If the try block doesn't succeed, it will still be false.
-
M K over 10 yearsYes, I came back to remove it.
-
Axel over 10 years@RohitJain
RuntimeException
extendsException
so catchingException
will also catchRuntimeException
which is not a good programming practice. -
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 over 10 yearsYou would get
java.lang.ArrayIndexOutOfBoundsException: 1
for inputs like "test", "abc" etc.. -
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 over 10 yearsYes, thank you, I forgot to remove the
[1]
when I copy/pasted the code. -
Rohit Jain over 10 years@Axel. Yeah true. That should have been the comment. Catching Exception is not a good idea.
-
Axel over 10 yearsYes, a bit more compact than my version. But you also should handle
null
return value ofJOptionPane.showInputDialog()
(I think it might be returned if the dialog is closed using the controls in the window decoration or by hittingESC
but the documentation is somewhat unclear in this regard). -
M K over 10 yearsYou 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 over 10 yearsDepending 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 over 10 yearsYeah a null check is needed before calling split() on fullName.
-
Axel over 10 years@Aswin R I rejected your edit because it introduced an error. See my comment to Jayamohans solution.
-
Mohayemin over 10 years@sᴜʀᴇsʜᴀᴛᴛᴀ: OP was catching IOException. You could catch that too.