Smaller Try-Blocks Are Better

The following text is a partial translation of the original English article, performed by ChatGPT (gpt-3.5-turbo) and this Jekyll plugin:

通常情况下,尤其是在Java中,方法中的一些地方可能会引发异常。通常情况下,我们会使用一个大的try块,底部只有一个catch块。我们捕获所有的异常,通常还会使用分组。这有助于我们最小化异常捕获所产生的干扰。然而,这样的大的try块会危及可维护性:我们无法在catch块内提供适当的错误上下文。

除了使用System.out而不是注入的依赖之外,你认为这个Java方法有什么问题?

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Pattern;

void grep(Path file, Pattern regex) { try { for (String line : Files.readAllLines(file)) { if (regex.matcher(line).matches()) { System.out.println(line); } } } catch (IOException ex) { throw new IllegalStateException(ex); } } ```

我认为它的try/catch块太大了。`IOException` 只会被 [`readAllLines`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-) 静态方法抛出,但是该块包含了其他几个方法调用和语句。以下代码会更好:

void grep(Path file, Pattern regex) { String[] lines; try { lines = Files.readAllLines(file); } catch (IOException ex) { throw new IllegalStateException(ex); } for (String line : lines) { if (regex.matcher(line).matches()) { System.out.println(line); } } }


现在的try/catch块仅覆盖异常可能发生的确切位置。没有其他的!

为什么较小的try块更好?因为它们能够提供更具焦点的错误报告和更详细的上下文。例如,第二个代码片段可以重写如下:

void grep(Path file, Pattern regex) { String[] lines; try { lines = Files.readAllLines(file); } catch (IOException ex) { throw new IllegalStateException( String.format( “Failed to read all lines from %s”, file ), ex ); } for (String line : lines) { if (regex.matcher(line).matches()) { System.out.println(line); } } } ```

我们能对第一个片段做同样的操作吗?我们可以,但是错误信息将会不准确,因为这个代码块涵盖了太多内容。

Translated by ChatGPT gpt-3.5-turbo/35 on 2023-09-06 at 20:26

sixnines availability badge   GitHub stars