-1

Just trying out a simple example to understand exception handling when it comes to streaming with foreachordered. Please write down suggestions on how we can continue performing actions on next element of list(20) when the current element threw exception (1).

  try {
      List<Integer> list = Arrays.asList(10, 1, 20, 15, 2); 
      list.stream().forEachOrdered(num->{
          if(num>2) {
              System.out.println(num);
          }else {
              int result=num/0;
              System.out.println(result);
          }
      });
      
      
  }catch(Exception e) {
      System.out.println("Exception: "+e);
      
  }
Megha C R
  • 5
  • 3

1 Answers1

0

In order to continue the cycle you need to catch the exception within it

List<Integer> list = Arrays.asList(10, 1, 20, 15, 2); 
list.stream().forEachOrdered(num -> {
    if(num > 2) {
        System.out.println(num);
    } else {
        try {
            int result = num/0;
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

This way when the exception is caught and handled it doesn't interfere with the next cycle. You could of course put the whole condition from if into the try-catch block, but there is no reason to do so.

Dropout
  • 13,653
  • 10
  • 56
  • 109