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

时间:2013-09-26 05:22:15

标签: java exception exception-handling try-catch

有没有办法做到这一点?

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

我想我可以使用扫描仪代替,但我很好奇是否有办法在捕获异常后重复try语句。

9 个答案:

答案 0 :(得分:7)

这样的东西?

while(condition){

    try{

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

    }

}

答案 1 :(得分:2)

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

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

    }
}

答案 2 :(得分:1)

您可以使用https://github.com/bnsd55/RetryCatch

示例:

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

您可以传递自己的匿名函数来代替new ExampleRunnable()

答案 3 :(得分:0)

您需要递归

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

答案 4 :(得分:0)

只需在循环中放入try..catch。

答案 5 :(得分:0)

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

答案 6 :(得分:0)

这肯定是一个简化的代码片段,因为在这种情况下我只是简单地删除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);
}

编辑:JOptionPane.showInputDialog可能会返回之前未处理的null。还修了一些拼写错误。

答案 7 :(得分:0)

showInputDialog()的签名是

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

和split()的是

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

然后扔掉IOException。那你怎么抓住它?

无论如何,你的问题的可能解决方案是

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

无需尝试捕获。自己试了一下。它工作正常。

答案 8 :(得分:0)

使用外部库可以吗?

如果有,请查看Failsafe

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

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

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

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