从 try-catch 块返回值的正确方法是什么?

由于缺少返回值而无法工作的示例:


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;

}

但它看起来很丑。有没有更自然的方法来解决这个任务?


芜湖不芜
浏览 125回答 4
4回答

MYYA

以下是一些可能的解决方案:将方法签名更改为public void writeToFile().&nbsp;不要退回Path.&nbsp;(但这可能对你不起作用:你可能需要.Path)return null;在方法末尾添加。这样做的缺点是调用者需要处理null返回的情况......否则当他们尝试使用不存在的 时它将获得 NPE&nbsp;Path。这相当于您的“丑陋”解决方案。从风格的角度来看,哪个更好是值得商榷的。(一个教条的“结构化编程”人会说你的方式更好!)更改签名以返回为Optional<Path>.&nbsp;这是比返回显式更好的选择null。如果你正确地实现它,调用者实际上被迫处理“缺席”的情况。删除try catch并将方法的签名更改为public Path writeToFile() throws IOException.&nbsp;调用者必须处理已检查的异常,但这可能是件好事!我应该指出您的代码没有正确处理资源。您应该对资源使用 try以确保由创建的流FileWriter始终关闭。否则存在泄漏文件描述符的风险,最终可能导致意外的 I/O 错误。

绝地无双

如果您不想返回,null我会更喜欢使用Optionaljava 8public Optional<Path> writeToFile() {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Path tempFilePath = Files.createTempFile(Paths.get(""), "sorting_test_", ".txt");&nbsp; &nbsp; &nbsp; &nbsp; BufferedWriter bw = new BufferedWriter(new FileWriter(tempFilePath.toFile()));&nbsp; &nbsp; &nbsp; &nbsp; for (List<Integer> arr : arrays) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Convert array ints to strings, join it to single string and write&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bw.write(arr.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(String::valueOf)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.joining(" ")));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bw.newLine();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; bw.close();&nbsp; &nbsp; &nbsp; &nbsp; return Optional.of(tempFilePath);&nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; &nbsp;return Optional.empty()}所以在调用者方法中你可以使用public void ifPresent(消费者消费者)或者公共布尔 isPresent()

潇湘沐

我不知道你为什么要寻找更“自然”的解决方案,但你可以return null在你的 catch 块中。

斯蒂芬大帝

另一种解决方案不是吃IOException(反模式),而是将其转换为适当的子类RuntimeException并从 catch 块中抛出。此外,在您的示例中,您正在泄漏文件处理程序,而不是关闭FileWriter异常。public Path writeToFile() {&nbsp; &nbsp; final Path tempFilePath;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; tempFilePath = Files.createTempFile(Paths.get(""), "sorting_test_", ".txt");&nbsp; &nbsp; } catch (IOException e ) {&nbsp; &nbsp; &nbsp; &nbsp; throw new MyRuntimeException(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Cannot create sorting_test temp file",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; &nbsp; try (final FileWriter fw = new FileWriter(tempFilePath.toFile())) {&nbsp; &nbsp; &nbsp; &nbsp; try(final BufferedWriter bw = new BufferedWriter(fw)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (List<Integer> arr : arrays) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Convert array ints to strings, join it to single string and write&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bw.write(arr.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(String::valueOf)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.joining(" ")));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bw.newLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return tempFilePath;&nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; throw new MyRuntimeException(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Cannot write to " + tempFilePath,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java