第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

從 try-catch 塊返回值的正確方法是什么?

從 try-catch 塊返回值的正確方法是什么?

蕪湖不蕪 2022-11-02 10:11:20
由于缺少返回值而無法工作的示例:public Path writeToFile() {    try {        Path tempFilePath = Files.createTempFile(Paths.get(""), "sorting_test_", ".txt");        BufferedWriter bw = new BufferedWriter(new FileWriter(tempFilePath.toFile()));        for (List<Integer> arr : arrays) {            // Convert array ints to strings, join it to single string and write            bw.write(arr.stream()                    .map(String::valueOf)                    .collect(Collectors.joining(" ")));            bw.newLine();        }        bw.close();        return tempFilePath;    } catch (IOException e) {        e.printStackTrace();    }}我知道我可以這樣做:public Path writeToFile() {    Path tempFilePath = null;    //try-catch{...}    return tempFilePath;}但它看起來很丑。有沒有更自然的方法來解決這個(gè)任務(wù)?
查看完整描述

4 回答

?
MYYA

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊

以下是一些可能的解決方案:

  • 將方法簽名更改為public void writeToFile(). 不要退回Path. (但這可能對你不起作用:你可能需要.Path

  • return null;在方法末尾添加。這樣做的缺點(diǎn)是調(diào)用者需要處理null返回的情況......否則當(dāng)他們嘗試使用不存在的 時(shí)它將獲得 NPE Path

    這相當(dāng)于您的“丑陋”解決方案。從風(fēng)格的角度來看,哪個(gè)更好是值得商榷的。(一個(gè)教條的“結(jié)構(gòu)化編程”人會(huì)說你的方式更好?。?/p>

  • 更改簽名以返回為Optional<Path>. 這是比返回顯式更好的選擇null。如果你正確地實(shí)現(xiàn)它,調(diào)用者實(shí)際上被迫處理“缺席”的情況。

  • 刪除try catch并將方法的簽名更改為public Path writeToFile() throws IOException. 調(diào)用者必須處理已檢查的異常,但這可能是件好事!


我應(yīng)該指出您的代碼沒有正確處理資源。您應(yīng)該對資源使用 try以確保由創(chuàng)建的流FileWriter始終關(guān)閉。否則存在泄漏文件描述符的風(fēng)險(xiǎn),最終可能導(dǎo)致意外的 I/O 錯(cuò)誤。


查看完整回答
反對 回復(fù) 2022-11-02
?
絕地?zé)o雙

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊

如果您不想返回,null我會(huì)更喜歡使用Optionaljava 8


public Optional<Path> writeToFile() {

    try {

        Path tempFilePath = Files.createTempFile(Paths.get(""), "sorting_test_", ".txt");

        BufferedWriter bw = new BufferedWriter(new FileWriter(tempFilePath.toFile()));


        for (List<Integer> arr : arrays) {

            // Convert array ints to strings, join it to single string and write

            bw.write(arr.stream()

                    .map(String::valueOf)

                    .collect(Collectors.joining(" ")));

            bw.newLine();

        }

        bw.close();


        return Optional.of(tempFilePath);

    } catch (IOException e) {

        e.printStackTrace();

    }

   return Optional.empty()

}

所以在調(diào)用者方法中你可以使用


public void ifPresent(消費(fèi)者消費(fèi)者)


或者


公共布爾 isPresent()


查看完整回答
反對 回復(fù) 2022-11-02
?
瀟湘沐

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊

我不知道你為什么要尋找更“自然”的解決方案,但你可以return null在你的 catch 塊中。



查看完整回答
反對 回復(fù) 2022-11-02
?
斯蒂芬大帝

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊

另一種解決方案不是吃IOException(反模式),而是將其轉(zhuǎn)換為適當(dāng)?shù)淖宇怰untimeException并從 catch 塊中拋出。


此外,在您的示例中,您正在泄漏文件處理程序,而不是關(guān)閉FileWriter異常。


public Path writeToFile() {


    final Path tempFilePath;

    try {

        tempFilePath = Files.createTempFile(Paths.get(""), "sorting_test_", ".txt");

    } catch (IOException e ) {

        throw new MyRuntimeException(

                "Cannot create sorting_test temp file",

                e

            );

    }


    try (final FileWriter fw = new FileWriter(tempFilePath.toFile())) {

        try(final BufferedWriter bw = new BufferedWriter(fw)) {

            for (List<Integer> arr : arrays) {

                // Convert array ints to strings, join it to single string and write

                bw.write(arr.stream()

                    .map(String::valueOf)

                    .collect(Collectors.joining(" ")));

                bw.newLine();

            }

        }


        return tempFilePath;

    } catch (IOException e) {

        throw new MyRuntimeException(

                "Cannot write to " + tempFilePath,

                e

            );

    }

}


查看完整回答
反對 回復(fù) 2022-11-02
  • 4 回答
  • 0 關(guān)注
  • 154 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號