finally
블록으로 명시해야 했던 것을 간편화☕ Ex01.java
public static void openFile1 (String path) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(path));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.printf("⚠️ %s 파일 없음%n", path);
} finally {
System.out.println("열었으면 닫아야지 ㅇㅇ");
if (scanner != null) scanner.close();
// 💡 만약 이 부분을 작성하는 것을 잊는다면?
}
}
String correctPath = "./src/sec09/chap04/turtle.txt";
String wrongPath = "./src/sec09/chap04/rabbit.txt";
openFile1(correctPath);
openFile1(wrongPath);
public static void openFile2 (String path) {
// ⭐ Scanner가 Closable - AutoClosable를 구현함 확인
try (Scanner scanner = new Scanner(new File(path))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.printf("⚠️ %s 파일 없음%n", path);
}
// 💡 .close를 작성하지 않아도 자동으로 호출됨
}
System.out.println("\\n- - - - -\\n");
openFile2(correctPath);
openFile2(wrongPath);
☕ OpFailException.java
public class OpFailException extends Exception {
public OpFailException() {
super("💀 작전 실패");
}
}
☕ SuicideSquad.java
public class SuicideSquad implements AutoCloseable {
public void doSecretTask () throws OpFailException {
if (new Random().nextBoolean()) {
throw new OpFailException();
};
System.out.println("🔫 비밀 작전 수행");
}
@Override
public void close() throws Exception {
System.out.println("💣 전원 폭사\\n- - - - -\\n");
}
}
☕ Ex02.java
public static void dirtyOperation () {
try (SuicideSquad sc = new SuicideSquad()) {
sc.doSecretTask();
} catch (OpFailException e) {
// 💡 예외상황은 아만다 윌러가 책임짐
e.printStackTrace();
System.out.println("🗑️ 증거 인멸\\n- - - - -\\n");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
for (int i = 0; i < 10; i++) {
dirtyOperation();
}