The above function interface means to open a file and do something within certain chars or length.. In my lambda code, I would do things like
Now, since it works with File, compiler would require you to catch certain exceptions.. But in the function interface, do we need to throw any Exception ? You know, sometimes the exception is really related to individual implementation, i.e. different lambda impl can generate diff exceptions. So, should we "throws..." in interface method at all ?
Linwood Hayes wrote:Thanks Jeanne. I can understand that I let the code that enclosing lambda implementation do the try/catch stuff. But I don't understand why I need to re-throw it as Runtime exception ? why can't I just handle the checked exception ?
Make it little clearer what I meant
Is this OK and good practice ?
I actually got so annoyed by the number of times I had to catch IOException and wrap it (in an UncheckedIOException, the best wrapper for IOExceptions since Java 8), I wrote a copy of all interfaces in java.util.function: https://robtimus.github.io/io-functions/. All can quite easily be converted to their equivalent in java.util.function using the provided unchecked methods.
I've also written an SQLException equivalent at https://robtimus.github.io/sql-functions/, but I doubt that will be used often.
The reason you can't just add a throws clause, though, is because the lambda is the implementation of the single abstract method in a functional interface, and you can't modify that method signature. Heck, you don't even see the method name when you write your lambda.
We're still dealing with several decisions made by the designers of Java at the birth of the language. Checked exceptions was one of them.
Kenneth A. Kousen wrote:We're still dealing with several decisions made by the designers of Java at the birth of the language. Checked exceptions was one of them.
You're saying that as if checked exceptions are a bad thing. I think it's one of the finest parts of the Java language. When I compare programs I've written in Java and programs I've written in C#, my Java programs are so much more robust because I'm forced to think about what I do with my exceptions.
I know that one of the designers wrote something along the lines of regretting adding checked exceptions to the language, but I believe they were on the right path.
You can create a language that very elegantly incorporates checked exceptions and lambda expressions, but your API must be designed with both features in mind.