← Back to Gists

Optional orElseThrow

📝 Java
stevenandrews
stevenandrews · Level 4 ·

Use Optional's orElseThrow to elegantly retrieve a value or throw a custom exception if it's null.

Java
import java.util.Optional; public class Example { public static void main(String[] args) { Optional<String> opt = Optional.ofNullable(null); String result = opt.orElseThrow(() -> new IllegalStateException("Value is missing!")); System.out.println(result); }
}

Comments

No comments yet. Start the discussion.