An abbreviation of my code:
It's more complicated than this but the problem I'm running into is that "someMethod()" is declared to throw an SQLException and Eclipse insists that the method call should be wrapped in a try/catch block. My enclosing method is already declaring that it throws an SQLException and I don't want to catch it.
Is there a way to handle this situation? I can do it with a non-streaming for() loop but I was hoping to use Streams.
This sort of question suggests to me that there is a disconnect between the concept of checked exceptions, and the structure of a stream; a proper functional program shouldn't throw any exceptions at all because they constitute side‑effects. Oracle have had a go at that problem with the introduction of this!
What do you want to happen if an exception is thrown? Can you ignore Eclipse's warning? Can you swap the exception for an unchecked one?
Why force it? You're using streams, but you're still doing procedural programming. There's nothing sexy about Stream.forEach(). Just use an enhanced for-loop, which is exactly the right tool for this job.
Yeah, unfortunately checked exceptions don't play well with streams. Yes, for forEach you can just switch to using a conventional for, but there are many other useful stream libraries where it's not as easy to switch.
Then again, checked exceptions don't play well with a lot of things, and it's worth noting that of the various languages created after Java, while many took good ideas from Java, essentially none (that I know of) have imitated the concept of checked exceptions.
So, simple preferred solution: use Kotlin.
But since many of us are still stuck with Java (esp. at work) for various reasons, and many existing libraries use java.util.function.* interfaces, I recommend a suite of helper methods to smooth it out. You need new set of interfaces that mirror java.util.function.* and the like, but allow checked exceptions. Then a bunch of methods to convert the checked versions to standard versions, all by catching the checked exception and rethrowing as an unchecked. This will allow your forEach code to become something like:
A shortened version of Unchecked is:
The full version has converters for *all* the interfaces in java.util.function.
Mike Simmons wrote:But since many of us are still stuck with Java (esp. at work) for various reasons, and many existing libraries use java.util.function.* interfaces, I recommend a suite of helper methods to smooth it out. You need new set of interfaces that mirror java.util.function.* and the like, but allow checked exceptions.