【问题标题】:Java Catch error and continue running to the nextJava Catch 错误并继续运行到下一个
【发布时间】:2018-10-22 17:55:41
【问题描述】:

我无法找到一种方法来让我的程序在捕获并出错后继续运行。 例如,我有:

String[] num={"1","2","3","NotNumber","4","5"};       

我想全部转换成整数,所以num[3] 无效,但我想在它捕获错误后继续运行到num[4]num[5]。 我该怎么做?

【问题讨论】:

  • 试试这个sample的代码,我相信它会起作用。

标签: java


【解决方案1】:

如果您已经展示了到目前为止所尝试的内容,那将会有所帮助,但最简单的解决方案是将您的 int.parse() 包装在 try/catch 块中并吞下异常。

for(int i = 0; i < items.length; i++) {
    try {
        newItems[i] = Itemger.parseInt(items[i]);
    catch(Exception ex) {
        // do nothing
    }
}

【讨论】:

    【解决方案2】:

    try-catch 块放入您的迭代中

    JAVA 7

    List<Integer> intList = new ArrayList<>();
    for(String s : num) {
      try {
        Integer n = Integer.valueOf(s);
        intList.add(n);
      } catch (Exception ex) { continue; }
    }
    

    JAVA 8 流

    List<Integer> intList = Arrays.asList(num)
      .stream()
      .map(s -> {
        try {
          return Integer.valueOf(s);
        } catch(Exception ex) { return null;}
      })
      .filter(i -> i != null)
      .collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-14
      • 2012-03-12
      • 2017-09-23
      • 1970-01-01
      • 2021-01-22
      • 2012-06-04
      • 2020-07-08
      • 1970-01-01
      相关资源
      最近更新 更多