user8539826
user8539826

Reputation: 31

Handling exception in Lambda Expression

What will be the equivalent lambda expression for below code?

List<String> List = new ArrayList<String>();
for (String var: alreadyList) {
     try {
         if (getNumber(var) == num) {
             filteredList.add(var);
         }
     } catch(NullPointerException exception) {
           throw exception;
     }
 }

This is usual lambda expression but how to throw the Nullpointerexception in it?

List<String> List = alreadyList.stream()
            .filter(var -> getNumber(var) == num)
            .collect(Collectors.toList());

Upvotes: 2

Views: 128

Answers (3)

Nikolas
Nikolas

Reputation: 44398

Never catch the unchecked exceptions including the NullPointerException. The way you do is just rethrowing it. Either filter out the null values out.

List<String> List = alreadyList.stream()
                               .filter(Objects::nonNull)
                               .filter(var -> getNumber(var) == num)
                               .collect(Collectors.toList());

The code you have provided:

List<String> List = alreadyList.stream()
                               .filter(var -> getNumber(var) == num)
                               .collect(Collectors.toList());

Will already throw the NullPointerException in case getNumber(var) would fail. Your try-catch does not do anything different.

Upvotes: 1

GBlodgett
GBlodgett

Reputation: 12819

Catching a NPE is bad practice. NPE is an unchecked exception. From the docs:

If an argument is null, the method might throw a NullPointerException, which is an unchecked exception.

Instead why not add another filter to the stream:

List<String> List = alreadyList.stream()
        .filter(e -> e!= null)
        .filter(var -> getNumber(var) == num)
        .collect(Collectors.toList());

Upvotes: 3

Andrei Prakhov
Andrei Prakhov

Reputation: 206

It is bad practice to catch NullPointerException. You can use Optional class to avoid it and do necessary action only if object is present. You can throw other exceptions from your getNumber() method without any problems

Upvotes: 2

Related Questions