Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw an exception if an Optional<> is present

Tags:

java

java-8

Let's say I want to see if an object exists in a stream and if it is not present, throw an Exception. One way I could do that would be using the orElseThrow method:

List<String> values = new ArrayList<>(); values.add("one"); //values.add("two");  // exception thrown values.add("three"); String two = values.stream()         .filter(s -> s.equals("two"))         .findAny()         .orElseThrow(() -> new RuntimeException("not found")); 

What about in the reverse? If I want to throw an exception if any match is found:

String two = values.stream()         .filter(s -> s.equals("two"))         .findAny()         .ifPresentThrow(() -> new RuntimeException("not found")); 

I could just store the Optional, and do the isPresent check after:

Optional<String> two = values.stream()         .filter(s -> s.equals("two"))         .findAny(); if (two.isPresent()) {     throw new RuntimeException("not found"); } 

Is there any way to achieve this ifPresentThrow sort of behavior? Is trying to do throw in this way a bad practice?

like image 642
mkobit Avatar asked Feb 19 '15 00:02

mkobit


People also ask

How do you throw an exception if optional not present?

The orElseThrow() method of java. util. Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.

What exception is thrown by optional get when not nested?

NoSuchElementException Exception Via orElseThrow() Since Java 10. Using the Optional. orElseThrow() method represents another elegant alternative to the isPresent()-get() pair. Sometimes, when an Optional value is not present, all you want to do is to throw a java.

How do you handle optional exceptions?

The technique used in Optional for error handing is similar to the old one (in C or even go), returning error codes to handle exceptions. But instead of error code we return a generic type called Optional which indicates presence or absence of a value.


1 Answers

You could use the ifPresent() call to throw an exception if your filter finds anything:

    values.stream()             .filter("two"::equals)             .findAny()             .ifPresent(s -> {                 throw new RuntimeException("found");             }); 
like image 61
beresfordt Avatar answered Nov 12 '22 01:11

beresfordt