I would like to simulate an optional .ifPresentThrow() to use somenthing like:
.ifPresent(MyException::go)
and not use:
.ifPresent(e -> {
throw new MyException();
})
so I created my class with the go method:
class MyException extends RuntimeException {
static void go() {
throw new MyException();
}
}
it's not work because the ifPresent hopes to receive a consumer x -> (), not a runnable () -> ()
adding some param to the function, I will have a unused param.
what's the best way to do this?
As you've already understood, Functional interface doesn't match - ifPresent()
expects a Consumer<? super T>
. But MyException::go
isn't a consumer, since go()
doesn't take any arguments.
To fix it, you need to change the method signature of go()
:
public class MyException extends RuntimeException {
static void go(Object o) {
throw new MyException();
}
}
Note: it's only a dummy example.
Usually, when you're creating a custom Exception you're having in mind a particular use case, and this exception would not be something ubiquitous like standard exceptions (for instance, if you have a need to create your custom subclass of AuthenticationException
you would not expect it to be thrown in any part of your application, it might only occur while validating authentication data of the request).
Let's expend the example shown above.
Assume we have a domain class:
@Getter
public class MyCustomObject {
private String name;
}
And MyException
is designed to describe abnormal situations which might occur while using MyCustomObject
or its subclasses. Argument expected by go()
can be used to incorporate some properties of the domain object into the exception-message:
public class MyException extends RuntimeException {
public MyException(String message) {
super(message);
}
static void go(MyCustomObject o) {
throw new MyException(o.getName());
}
}
Example of usage:
Stream.of(new MyCustomObject("A"), new MyCustomObject("B"))
.filter(o -> !o.getName().matches("\\p{Upper}")) // retain instances having Invalid names
.findFirst()
.ifPresent(MyException::go); // invalid name was found -> throw an Exception with the name included into a message