1

I am looking for a way to handle null with an Exception using Constructor reference with Optional, where I want to pass a custom message with Exception.

E.g. There is a service which offers getPassword(String userId) method to retrieve the password. It accepts one argument of type String, which is the userId. If the userId does not exist in the system, then it returns null, else returns password (String). Now I am calling this method and want to throw 'IllegalArgumentException' if null is returned.

I know there are many ways to do this in Java, but I am looking for a way to do it with Optional using Constructor reference.

//calling getPassword() method to retrieve the password for given userId - "USER_ABC", but there is no such user so null will be returned.
String str = service.getPassword("USER_ABC");

// I want to throw the exception with a custom message if value is null
// Using Lambda I can do it as below.
Optional<String> optStr = Optional.ofNullable(str).orElseThrow(() -> new IllegalArgumentException("Invalid user id!"));

// How to do it using Constructor Reference. How should I pass message ""Invalid user id!" in below code.
Optional<String> optStr = Optional.ofNullable(str).orElseThrow(IllegalArgumentException::New);
Ajay Singh
  • 441
  • 6
  • 18

2 Answers2

3

but I am looking for a way to do it with Optional using Constructor reference.

You can, when your Exception has a no-arg constructor:

Optional.ofNullable(null).orElseThrow(RuntimeException::new);

This is basically the same as:

Optional.ofNullable(null).orElseThrow(() -> new RuntimeException());

The arguments of the lambda and the arguments of the constructor must match to use method reference. For example: **()** -> new RuntimeException**()** or **(String s)** -> new RuntimeException**(s)**.

When they don't match, you can't use a method reference.


Or you can use some ugly workaround:

Optional.ofNullable(null).orElseThrow(MyException::new);

class MyException extends RuntimeException {
  public MyException() {
    super("Invalid user id!");
  }
}

But that's a lot of overhead for no good reason.

Benjamin M
  • 23,599
  • 32
  • 121
  • 201
  • Thanks @Benjamin M ! As you mentioned, it would certainly be better to use lambda in this case, than ugly workaround. – Ajay Singh Mar 05 '21 at 09:43
0

It not possible with lambda function. Reference How to pass argument to class constructor when initialzed thru ::new in Java8

Anand Kumar
  • 156
  • 7