java - लैम्ब्डा से अपवाद फेंकना
error-handling lambda (2)
समस्या यह है कि @FunctionalInterface
उपयोग किए गए सभी @FunctionalInterface
, अपवादों को फेंकने की इजाजत नहीं देते हैं, @FunctionalInterface
अपवादों के लिए सहेजते हैं।
एक समाधान मेरा एक पैकेज का उपयोग कर रहा है ; इसके साथ, आपका कोड पढ़ सकता है:
sessions.parallelStream()
.map(Session::getBasicRemote)
.forEach(Throwing.consumer(basic -> basic.sendText(message)));
return this;
इस सवाल का पहले से ही उत्तर दिया गया है:
इस जावा 8 कोड को देखते हुए
public Server send(String message) {
sessions.parallelStream()
.map(Session::getBasicRemote)
.forEach(basic -> {
try {
basic.sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
});
return this;
}
कैसे हम इस IOException
को विधि कॉल के स्टैक को सौंप दिया जाए? (संक्षेप में कैसे इस पद्धति को IOException
फेंकने के लिए?)
जावा में लैम्ब्डास त्रुटि संभाल करने के लिए बहुत अनुकूल नहीं लग रहा है ...
मैंने स्ट्रीम एपीआई के लिए एक एक्सटेंशन लिखा था जो फेंका जाने वाले चेक अपवादों की अनुमति देता है।
public Server send(String message) throws IOException {
ThrowingStream.of(sessions, IOException.class)
.parallelStream()
.map(Session::getBasicRemote)
.forEach(basic -> basic.sendText(message));
return this;
}