← SEARCHABLE ARCHIVE
Java · 2026-08-06

Java from Basics to Mastery — Part 7

Handling failure with exceptions and try-with-resources

INTERACTIVE READING MODE →

The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.

File, network, and input values ​​can fail at any time. Java's exception and resource management syntax is used to propagate failures and close resources on any path.

Passing Exceptions

public Settings loadSettings(Path path) throws IOException {
    String json = Files.readString(path);
    return parser.parse(json);
}

Don't force an exception to be hidden internally if the caller must decide how to recover. When adding context, you must preserve the original exception as the cause.

try {
    settings = loadSettings(path);
} catch (IOException error) {
    logger.warn("settings load failed", error);
    settings = Settings.defaults();
}

Only catch exceptions that can be handled. If you catch all Exceptions and do nothing, even actual bugs can proceed as normal.

try-with-resources

public List<String> readLines(Path path) throws IOException {
    try (BufferedReader reader = Files.newBufferedReader(path)) {
        return reader.lines().toList();
    }
}

If you create an object that implements AutoCloseable within parentheses, close will be called at the end of the block. File handles are cleaned up on both normal return and exception paths.

Checked exceptions and runtime exceptions

Checked exceptions reveal whether they are handled by method declaration or catch. Runtime exceptions such as IllegalArgumentException are often used for invalid calling contracts or programming errors.

Which of the two is not necessarily better, but the criterion is whether it is a failure that the caller can recover from.

Replace after completing the state

Settings loaded = loadSettings(path);
currentSettings = loaded;

If you completely create a new value and enter it into the field, the existing settings will be maintained even if loading fails. Exception design is not about creating a lot of catches, but about determining how resources and object state remain in case of failure.