# Io / Github / Biezhi / Java11 / Trywithresources

## Overview

This module is a demonstration of the **Try-With-Resources** feature in Java — a language construct introduced in **Java SE 7** for automatic resource management, and **improved in Java SE 9** to eliminate the need for effectively-final variables outside the try block. It lives within a larger collection of examples showcasing Java 11 features, but the try-with-resources pattern itself predates Java 11. The module serves as educational material, showing how a resource declared once outside a `try` statement can be automatically closed at the end of the block.

## Module Structure

```
io.github.biezhi.java11.trywithresources
└── Example.java
```

The module is a subpackage under the top-level `io.github.biezhi.java11` namespace. It contains no child modules or subpackages.

## Key Classes

### `Example`

**Source:** [Example.java](src/main/java/io/github/biezhi/java11/trywithresources/Example.java)

The sole class in this module. It is a public, top-level example class authored by *biezhi* that demonstrates a Java SE 9 improvement to try-with-resources.

#### Purpose

The class demonstrates a specific try-with-resources usage pattern that became possible starting in **Java SE 9**. Prior to Java 9, the resource variable had to be declared *inside* the try parentheses. Java 9 relaxed this requirement: if a resource variable is **effectively final** (i.e., not reassigned after initialization), it can be declared outside the try block and still be managed automatically.

#### Constructor

No explicit constructor — uses the default.

#### Methods

##### `main(String[] args)` — lines 18–25

**Signature:** `public static void main(String[] args) throws Exception`

**What it does:** Opens a `BufferedReader` wrapping a `FileReader` to read `./README.md` line by line, printing each line to `System.out`. The reader is declared **outside** the `try` block (line 19) and referenced **inside** the `try` block (line 20), which is the Java SE 9 improvement being demonstrated.

**Parameters:** `args` — standard command-line arguments (unused).

**Return:** `void`.

**Side effects:** Reads and prints the contents of `./README.md` to standard output. Throws `Exception` (the compiler requires this since `BufferedReader.readLine()` throws `IOException`).

**Key detail:** The resource variable `reader1` is initialized on line 19 *before* the try block. It is effectively final (never reassigned), so the Java SE 9 improvement allows it to be used directly in the `try (reader1)` statement on line 20. The reader is automatically closed when the try block exits, whether normally or via an exception.

#### Source code structure

```java
public class Example {

    public static void main(String[] args) throws Exception {
        BufferedReader reader1 = new BufferedReader(new FileReader("./README.md"));
        try (reader1) {
            while(reader1.ready()){
                System.out.println(reader1.readLine());
            }
        }
    }
}
```

## How It Works

### The Try-With-Resources Pattern

Try-with-resources is Java's mechanism for automatic resource cleanup. Any resource that implements `java.lang.AutoCloseable` (which includes `java.io.Closeable` subclasses like `BufferedReader` and `FileReader`) can be managed by a try-with-resources statement. The JVM guarantees that the `close()` method is called on each resource when the try block exits, regardless of whether the exit was normal or via an exception.

### The Java SE 7 vs Java SE 9 Difference

**Java SE 7** (original form):

```java
// Resource declared INSIDE the try — Java 7 style
try (BufferedReader reader = new BufferedReader(new FileReader("./README.md"))) {
    // use reader
}
// reader is closed automatically
```

**Java SE 9** (improved form — demonstrated in this module):

```java
// Resource declared OUTSIDE — Java 9 style
BufferedReader reader1 = new BufferedReader(new FileReader("./README.md"));
try (reader1) {
    // use reader1
}
// reader1 is closed automatically
```

The Java SE 9 improvement eliminates boilerplate when the resource is created before the try block (e.g., passed as a parameter, stored in a field, or shared across multiple try blocks). The only constraint is that the variable must be **effectively final**.

### Design Decision: Why a `while(reader1.ready())` Loop?

The example reads a file line-by-line using `reader1.ready()` to check if more data is available. This is a simple (though not the most robust) way to iterate over all lines. In production code, `BufferedReader.lines()` (Java 8+) or a simple `while ((line = reader.readLine()) != null)` loop would be preferred, but this example is intentionally minimal.

## Data Model

There are no data model classes, DTOs, or entity classes in this module. The module only demonstrates a language construct using standard JDK types (`BufferedReader`, `FileReader`).

## Dependencies and Integration

| Dependency | Source |
|---|---|
| `java.io.BufferedReader` | Java SE standard library |
| `java.io.FileReader` | Java SE standard library |

This module has no package-level dependencies on other modules within the repository. It is self-contained and uses only standard JDK classes.

## Design Notes for Developers

- **Educational purpose:** This module is part of the larger `io.github.biezhi.java11` example project (hosted at `github.com/biezhi/java11`). Each subpackage in that project demonstrates a specific Java feature with a minimal, focused example. This module's purpose is to teach the Java SE 9 improvement to try-with-resources.
- **No child modules:** There are no subpackages here. The module is intentionally minimal.
- **Resource leak protection:** The entire point of this pattern is to prevent resource leaks. If the try block throws an exception, `reader1.close()` is still called. If multiple resources were used, they would all be closed in reverse order of their creation.
- **Suppressed exceptions:** In the standard try-with-resources pattern, if an exception is thrown from the try block and another from `close()`, the latter is *suppressed* and attached to the former via `addSuppressed()`. This is handled transparently by the JVM.
- **File path is relative:** The example reads `./README.md` using a relative path. This resolves relative to the current working directory at runtime, not the source file location.

```mermaid
flowchart TD
    subgraph Module["io.github.biezhi.java11.trywithresources"]
        Example["Example
<bold>Class</bold>"]
    end

    subgraph JavaSE7["Java SE 7 Feature"]
        TryWithResources["Try-With-Resources
Automatic cleanup of AutoCloseable
resources at block exit"]
    end

    subgraph JavaSE9["Java SE 9 Improvement"]
        OutsideDeclaration["Resources declared
outside try block
(effectively final vars)"]
    end

    Example -->|demonstrates| TryWithResources
    TryWithResources -->|improved by| OutsideDeclaration
    Example -->|example usage| OutsideDeclaration

    classDef module fill:#e1f5fe,stroke:#01579b
    classDef feature fill:#e8f5e9,stroke:#1b5e20
    classDef improvement fill:#fff3e0,stroke:#e65100

    class Module module
    class JavaSE7 feature
    class JavaSE9 improvement
```
