0

I am trying to apply a function to a list of value, if in this function the value match, It returns an MyExceptions(a custom kind of Exceptions). I a use a single value like this:

myFunctions.checkValue(myValue);

I can throws MyExceptions directly in my function declaration, but if I have a list of value, I can't use the throws but I have to use try/catch. Like this:

public void firstCheckValue(String value1,List<String> listValue) throws MyException{
        myFunctions.checkValue(value1);
        listValue.stream().forEach(p->{
        try {
            listValue.checkValue(p);
        } catch (MyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    });
}

Why I can't use :

listValue.stream().forEach(p->myFunctions.checkValue(p));

And directly throws MyExceptions?

Naman
  • 27,789
  • 26
  • 218
  • 353
Liz Lamperouge
  • 681
  • 14
  • 38
  • Is this your IDE (Intellij) telling you that you can't use "Throws" or is the compiler giving you the error directly? – Rob de Witte Mar 11 '20 at 15:06
  • 1
    Because `forEach` accepts a `Consumer` argument and the `Consumer#accept` method is not capable of throwing checked exceptions. – Slaw Mar 11 '20 at 15:23
  • 2
    Also, if the sole operation on your stream is `forEach` then there's no reason to create a stream; just use `listValue.forEach(...)` directly (the method is inherited from `Iterable`). It'd be even better to simply use an enhanced for loop (e.g. `for (String p : listValue) { checkValue(p); }` as then you could throw your checked exception. – Slaw Mar 11 '20 at 15:27
  • @Slaw so there is not a "stream" approach for this? – Liz Lamperouge Mar 17 '20 at 11:58

2 Answers2

0

Try to use RuntimeException class as the parent of MyException

  • I can't, MyException is in a standard library that I have implemented and it is used by other project – Liz Lamperouge Mar 12 '20 at 14:49
  • In that case, move this code to a new method. Inside catch block write `throw new RuntimeException(e);` With this, you can wrap you checked exception to unchecked one. Anytime you can get your original exception with the `getCause()` method of RuntimeException – Bakhtiyor Begmatov Mar 12 '20 at 17:13
  • My MyExceptions class it's already extending a class, Exception. – Liz Lamperouge Mar 13 '20 at 10:47