1. 전통적인 try-finallty 방식 (Java 7 이전)
import java.util.Scanner;
public class OldStyleExample {
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(System.in);
System.out.print("숫자를 입력하세요: ");
int num = sc.nextInt();
System.out.println("입력된 숫자: " + num);
} finally {
// 반드시 리소스를 닫아야 하므로 finally에서 처리
if (sc != null) {
sc.close();
}
}
}
}
2. try-with-resources 방식 (Java 7 이상)
import java.util.Scanner;
public class NewStyleExample {
public static void main(String[] args) {
// try-with-resources: sc는 AutoCloseable이므로 자동으로 닫힘
try (Scanner sc = new Scanner(System.in)) {
System.out.print("숫자를 입력하세요: ");
int num = sc.nextInt();
System.out.println("입력된 숫자: " + num);
}
// 따로 close() 호출 필요 없음
}
}