Java – Is it allowed to throw a runtime exception from a java.util.Predicate

functional programmingjava

The java.util.Predicate interface contains the test(...) method, whose JavaDoc description states that it [evaluates] this predicate on the given argument and that it [returns] true if the input argument matches the predicate, otherwise false.

Should I take this to mean that test(..) always returns a true or a false and is never allowed to throw an exception? I ask, because the classes from the Collections framework have the concept of "optional operations", where it is explicitly mentioned in the JavaDoc that certain methods might throw UnsupportedOperationException.

First of all, I'm not a Java programmer, I don't work in software development per se, but I use a language that is similar to Java in some respects and I try to follow Java conventions where possible. I've tried searching for resources on the topic, but most of them mention how to throw checked exceptions from stream code.

I'll try to make a contrived example here. Let's say I have a Person class and a Predicate defined like class IsAdult implements Predicate<Object>. Notice that I've used Predicate<Object> and not of Person. Would it be OK to throw an exception if the object being tested is not a Person, for which it's possible to determine whether they are an adult, or should the predicate return false, seeing as how the object that it tested couldn't under any circumstances have been an adult.

Best Answer

In this specific case, it probably doesn't make sense to throw an exception in most cases, because conceptually whatever you encounter either fulfills the predicate criteria or it doesn't.

If you have expected special cases that are neither "true" nor "false" but have some other meaning that needs to be handled differently, then using a Predicate is the wrong choice, and instead you want to use a Function that outputs e.g. an enum with three or more values.

Basically the main case where you'd want to throw a RuntimeException is when something happens that you didn't expect to happen, something that shows a serious problem (programming error, corrupt data, etc.) and where the only useful response is to abort whatever you were doing and run some special error handling code.