Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Intro to Java Web Development with Spark Bells and Whistles Accessing Specific Items

Florian Tönjes
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 50,856 Points

Why does the 'orElseThrow()' method take a Supplier as a parameter instead of an Exception?

What is the benefit of the orElseThrow() method to expect a Supplier instead of an Exception?

Why is it this:

public CourseIdea findBySlug(String slug) {
        return ideas.stream().filter(idea -> idea.getSlug().equals(slug))
                .findFirst()
                .orElseThrow(NotFoundException::new);
    }

Instead of this:

public CourseIdea findBySlug(String slug) {
        return ideas.stream().filter(idea -> idea.getSlug().equals(slug))
                .findFirst()
                .orElseThrow(new NotFoundException());
    }

Kind Regards, Florian

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Hi Florian Tönjes , great question!

The overarching concept here is that by providing a method reference (or a function) it can be lazily initialized. No need to create Exception object if you don't need it. Create it only when you need it.

We're planning on diving deeper into functional programming very soon, and that will help explore awesome questions like these.

That make sense?