---
# System prepended metadata

title: try-with-resources 的用法
tags: [ocpjp]

---

# try-with-resources 的用法
**Question:**
```java=
final class Folder { //line n1
    //line n2
    public void open() {
        System.out.print("Open");
    }
}
 
public class Test {
    public static void main(String[] args) throws Exception {
        try (Folder f = new Folder()) {
            f.open();
        }
    }
}
```
## Which two modifications enable the code to print Open Close?

**A. Replace line n1 with:**
```java=
class Folder implements AutoCloseable {
```
B. Replace line n1 with:
```java=
class Folder extends Closeable {
```
C. Replace line n1 with:
```java=
class Folder extends Exception {
```
D. At line n2, insert:
```java=
final void close() {
    System.out.print("Close");
}
```
**E. At line n2, insert:**
```java=
public void close() throws IOException {
    System.out.print("Close");
}
```
- [x] **Answer:AE**

- [參考網站](https://magiclen.org/ocpjp-try-with-resources-3/)

**要把物件當作try-with-resources的資源，該物件類別必須要實作AutoCloseable介面的close方法。**

---
**改良後程式碼如下:**
```java=
final class Folder implements AutoCloseable {// line n1
	@Override
	public void close() throws Exception { //line n2
		System.out.println("Close");
	}
	public void open() {
		System.out.print("Open");
	}
}

public class Test {
	public static void main(String[] args) {
		try (Folder f = new Folder()) {
			f.open();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
```

---
**Question:**
```java=
public static void main(String[] args) throws IOException {
    BufferedReader brCopy = null;
    try (BufferedReader br = new BufferedReader (new FileReader("employee.txt"))) { //line n1
            br.lines().forEach(c -> System.out.println(c));
            brCopy = br;//line n2
    }catch (Exception e) {
        System.out.println(e);
    }
    brCopy.ready(); //line n3;
}
```
## Assume that the ready method of the BufferedReader, when called on a closed BufferedReader,
throws an exception, and employee.txt is accessible and contains valid text.
What is the result?
A. A compilation error occurs at line n3.
B. A compilation error occurs at line n1.
C. A compilation error occurs at line n2.
**D. The code prints the content of the employee.txt file and throws an exception at line n3.**
- [x] **Answer: D**

- [參考網站](https://magiclen.org/ocpjp-try-with-resources-5/)
:::info
br變數所參考到的BufferedReader物件為try-with-resources結構的資源，因此在離開try-with-resources結構的try區塊後，資源就會被釋放(BufferedReader物件會close)。

line n3的部份在BufferedReader物件被close之後呼叫ready方法，所以會拋出IOException。
:::
###### tags: `ocpjp`
