日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Lambdas中的例外:有点混乱的优雅解决方案

發布時間:2023/12/3 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Lambdas中的例外:有点混乱的优雅解决方案 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

考慮以下用于寫入文件的功能:

該方法背后的想法是,以允許用戶在不同的實施方式中通過InputStream的方法,以便writeToFile可以被稱為例如用GZIPOuputStream , SnappyOuputStream
(快速壓縮)或簡單的FileInputStream 。

private static void writeToFile(File file, String value,Function<OutputStream, OutputStream> writing) throws IOException{try (PrintWriter pw = new PrintWriter(new BufferedOutputStream(writing.apply(new FileOutputStream(file))))) {pw.write(value);} }

這是一個整潔的函數,可以這樣調用:

public static void main(String[] args) {try {//Write with compression//DOES NOT COMPILE!!writeToFile(new File("test"), "Hello World", GZIPOutputStream::new);//Just use the FileOutputStreamwriteToFile(new File("test"), "Hello World", i->i);}catch(IOException e){//deal with exception as you choose} }

不幸的是,正如評論中指出的那樣,它無法編譯! 它之所以無法編譯,是因為GZIPOutputStream在其構造函數中引發了IOException 。 如果將IOException從lambda中拋出,然后可以在try catch塊中進行處理,那將是很好的選擇–但這不是lambda的工作方式:-(

實際上,這是您必須處理異常以使代碼得以編譯的方式:

public static void main(String[] args) {try {//Write with compression//COMPILES BUT SO UGLYwriteToFile(new File("test"), "Hello World", i -> {try {return new GZIPOutputStream(i);} catch (IOException e) {//HOW ARE WE SUPPOSED TO DEAL WITH THIS EXCEPTION??throw new AssertionError(e);}});//Just use the FileOutputStreamwriteToFile(new File("test"), "Hello World", i->i);}catch(IOException e){//deal with exception as you choose} }

這不僅難看,而且還給您帶來了如何處理IOException的尷尬問題。 在這種情況下,我們剛剛將其重新包裝在AssertionError中。 有關處理這種情況的正確方法,請參閱我以前的文章 “使用異常作弊”。

但是有解決此問題的方法。 可以使用創建帶有值的自定義函數來返回值并拋出Exception ,而不是使用帶有值并返回值的java.util.function.Function 。 這樣, writeToFile的客戶端代碼writeToFile干凈了,并且可以自然地處理異常。 而且,lambda現在以它們使我們的代碼更漂亮和更易于理解的方式使用。

請參閱下面的完整代碼清單:

package util;import java.io.*; import java.util.zip.GZIPOutputStream;public class LambdaExceptions {public static void main(String[] args) {try {//Write with compressionwriteToFile(new File("test"), "Hello World", GZIPOutputStream::new);//Just use the FileOutputStreamwriteToFile(new File("test"), "Hello World", i->i);}catch(IOException e){//deal with exception as you choose}}private static void writeToFile(File file, String value, ThrowingFunction<OutputStream, OutputStream, IOException> writing) throws IOException{try (PrintWriter pw = new PrintWriter(new BufferedOutputStream(writing.apply(new FileOutputStream(file))))) {pw.write(value);} }@FunctionalInterfacepublic interface ThrowingFunction<I, O, T extends Throwable> {O apply(I i) throws T;} }

翻譯自: https://www.javacodegeeks.com/2015/05/exceptions-in-lambdas-an-elegant-solution-to-a-bit-of-a-mess.html

總結

以上是生活随笔為你收集整理的Lambdas中的例外:有点混乱的优雅解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。