Java:Try/Catch 语句:捕获异常时,重复 try 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19019975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:26:42  来源:igfitidea点击:

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

javaexceptionexception-handlingtry-catch

提问by

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.

我想我可以为此使用扫描仪,但我只是想知道是否有办法在捕获异常后重复 try 语句。

采纳答案by Suresh Atta

Something like this ?

像这样的东西?

while(condition){

    try{

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

    }

}

回答by Mohayemin

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);
}

回答by Micha? Tabor

Just put try..catch inside while loop.

只需将 try..catch 放入 while 循环中。

回答by M K

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

一种方法是使用 while 循环并在正确设置名称后退出。

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

    }
}

回答by Andreas Dolk

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)

语言中没有“重试”,就像其他人已经建议的那样:创建一个外部 while 循环并在触发重试的“catch”块中设置一个标志(并在成功尝试后清除标志)

回答by Axel

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

这肯定是一个简化的代码片段,因为在这种情况下,我会简单地完全删除try/catch- IOException 永远不会被抛出。你可以得到IndexOutOfBoundsException,但在你的例子中,它真的不应该用异常处理。

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.showInputDialogmight return nullwhich wasn't handled before. Also fixed some typos.

编辑:JOptionPane.showInputDialog可能会返回null以前没有处理过的。还修正了一些错别字。

回答by Aniket Thakur

Signature of showInputDialog() is

showInputDialog() 的签名是

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

and that of split() is

而 split() 是

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

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

没有然后扔IOException。那你怎么抓?

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.

无需尝试捕获。我自己试过了。它工作正常。

回答by Johnny

Would it be ok to use external lib?

使用外部库可以吗?

If so, check out Failsafe.

如果是这样,请查看Failsafe

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

首先,您定义一个 RetryPolicy 来表示应该何时执行重试:

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:

然后,您使用 RetryPolicy 重试执行 Runnable 或 Callable:

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

回答by bnsd55

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

您可以使用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.

而不是new ExampleRunnable()你可以传递你自己的匿名函数。