简体   繁体   English

如果发生异常,如何继续循环迭代?

[英]How to continue loop iterations if an exception occurs?

Hey I'm totally finished with my try-catch block, but have question. 嘿,我的try-catch块完全完成了,但是有疑问。 I want to count how many words and numbers a string contains. 我想计算一个字符串包含多少个单词和数字。 For this i want to use a try - catch block. 为此,我想使用try-catch块。 I parse the String to an int, and if the output is false, I want to count the number of words within the catch block logic. 我将String解析为一个int,如果输出为false,我想计算catch块逻辑中的单词数。 But after the program enters the catch block, the program exits. 但是在程序进入catch块之后,程序退出。 I want to continue iterating through the loop following the caught error. 我想继续在捕获到的错误之后循环遍历。 How can I make this happen? 我怎样才能做到这一点?

    Scanner odczyt = new Scanner(System.in);
    String zdanie = odczyt.nextLine();
    String[] podzdania = zdanie.split(" ");
    boolean exception = false;
    int numberword = 0;

    try {

        for (int i = 0; i < podzdania.length; i++) {
            Integer.parseInt(podzdania[i]);
        }

    } catch (NumberFormatException e) {

        numberword++;

    }

Move the try-catch block within the loop: 在循环内移动try-catch块:

for (int i = 0; i < podzdania.length; i++) {
  try {
    Integer.parseInt(podzdania[i]);
  } catch (NumberFormatException e) {
    numberword++;
  }
}

I would avoid using exceptions as a flow control mechanism though. 我将避免使用异常作为流控制机制。 Check this StackOverflow question for alternatives to validate the string before actually parsing it. 在实际解析字符串之前,请检查此StackOverflow问题以获取替代方法来验证字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM