猿问

Java 捕获错误并继续运行到下一个

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

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

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


Helenr
浏览 377回答 2
2回答

浮云间

将try-catch块放在您的迭代中爪哇7List<Integer> intList = new ArrayList<>();for(String s : num) {&nbsp; try {&nbsp; &nbsp; Integer n = Integer.valueOf(s);&nbsp; &nbsp; intList.add(n);&nbsp; } catch (Exception ex) { continue; }}JAVA 8 流List<Integer> intList = Arrays.asList(num)&nbsp; .stream()&nbsp; .map(s -> {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; return Integer.valueOf(s);&nbsp; &nbsp; } catch(Exception ex) { return null;}&nbsp; })&nbsp; .filter(i -> i != null)&nbsp; .collect(Collectors.toList());

慕少森

如果您已经展示了迄今为止您尝试过的内容,那将会有所帮助,但最简单的解决方案是将您int.parse()的内容包装在一个try/catch块中并吞下异常。for(int i = 0; i < items.length; i++) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; newItems[i] = Itemger.parseInt(items[i]);&nbsp; &nbsp; catch(Exception ex) {&nbsp; &nbsp; &nbsp; &nbsp; // do nothing&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答