9

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.

Raidri
  • 17,258
  • 9
  • 62
  • 65

9 Answers9

9

Something like this ?

while(condition){

    try{

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

    }

}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

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

    }
}
M K
  • 356
  • 3
  • 8
  • 1
    No need for success = false; in catch. If the try block doesn't succeed, it will still be false. – Silviu Burcea Sep 26 '13 at 05:31
  • Yes, I came back to remove it. – M K Sep 26 '13 at 05:33
  • @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. –  Sep 26 '13 at 05:38
  • 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. – M K Sep 26 '13 at 05:55
  • 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.) – Axel Sep 26 '13 at 05:58
1

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)

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
1

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());
Johnny
  • 14,397
  • 15
  • 77
  • 118
1

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.

bnsd55
  • 318
  • 1
  • 10
0

You need a recursion

public void lastNameGenerator(){
    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.")
        lastNameGenerator();
    }
    System.out.println(lastName);
}
Mohayemin
  • 3,841
  • 4
  • 25
  • 54
  • 1
    This might result in StackOverflow if exception keeps on occurring. Just FYI. – Rohit Jain Sep 26 '13 at 05:25
  • 4
    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! – Nir Alfasi Sep 26 '13 at 05:26
  • What is IOException doing in the snippet? I know OP has mentioned it mistakenly. – Jayamohan Sep 26 '13 at 05:27
0

Just put try..catch inside while loop.

Michał Tabor
  • 2,441
  • 5
  • 23
  • 30
0

This sure is a simplified code fragment because in this case I'd simply remove the try/catch altogether - IOException is never thrown. You could get an IndexOutOfBoundsException, but in your example it really shouldn't be handled with exceptions.

public void lastNameGenerator(){
    String[] nameParts;
    do {
        String fullName = JOptionPane.showInputDialog("Enter your full name");
        nameParts = fullName != null ? fullName.split("\\s+") : null;
    } while (nameParts!=null && nameParts.length<2);
    String lastName = nameParts[1];
    System.out.println(lastName);
}

EDIT: JOptionPane.showInputDialog might return null which wasn't handled before. Also fixed some typos.

Axel
  • 13,939
  • 5
  • 50
  • 79
0

Signature of showInputDialog() is

public static java.lang.String showInputDialog(java.lang.Object message)
                                       throws java.awt.HeadlessException

and that of split() is

public java.lang.String[] split(java.lang.String regex)

None of then throw IOException. Then how are you catching it?

Anyway possible solution to your problem would be

public void lastNameGenerator(){
    String fullName = null;
    while((fullName = JOptionPane.showInputDialog("Enter your full name")).split("\\s+").length<2)  {
    }
    String lastName =  fullName.split("\\s+")[1];
    System.out.println(lastName);
}

No need of try-catch. tried it myself. It works fine.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • 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). – Axel Sep 26 '13 at 05:51
  • Yeah a null check is needed before calling split() on fullName. – Aniket Thakur Sep 26 '13 at 05:59