import java.util.StringTokenizer;
public class Unchecked1Demo {
public static void main(String[]args) {
String s = "Time is money";
StringTokenizer st = new StringTokenizer(s);
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
System.out.println(st.nextToken()); // 더이상 나올 토크이 없는데 토큰 호출
}
}
public class Unchecked2Demo {
public static void main(String[]args) {
int[] arr = {0,1,2};
System.out.println(arr[3]); // 존재하지 않는 인덱스의 배열 호출
}
}
public class TryCatch1Demo {
public static void main(String[]agrs) {
int[] arr = {0,1,2};
try {
System.out.println("배열의 첫번째 원소 : " + arr[0]);
System.out.println("배열의 마지막 원소 : " + arr[3]);
System.out.println("배열의 중간 원소 : " + arr[1]); // 위에서 예외가 발생해서 실행되지 않는다.
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("원소가 존재하지 않습니다.");
}finally {
System.out.println("어이쿠!");
}
}
}
public class TryCatch2Demo {
public static void main(String[] args) {
int dividend = 10;
try {
int divisor = Integer.parseInt(args[0]);
System.out.println(dividend / divisor); // 10을 args에 입력받은 숫자로 나누기
} catch (ArrayIndexOutOfBoundsException e) { // args에 아무것도 입력하지 않았을 경우
System.out.println("원소가 존재하지 않습니다.");
} catch (NumberFormatException e) { // args에 문자를 넣었을 경우
System.out.println("숫자가 아닙니다.");
} catch (ArithmeticException e) { // args에 0을 넣었을 경우
System.out.println("0으로 나눌 수 없습니다.");
} catch (Exception e) { // 최상위 예외 객체라 맨 밑으로 와야 한다.
System.out.println("몰라"+e.getMessage());
} finally { // 예외 유무와 상과 없이 실행
System.out.println("항상 실행됩니다.");
}
System.out.println("종료.");
}
}
Try ~ with ~ resource문
try (자원) {
} catch (...) {
}
try 블록에서 자원을 사용했다면, try 블록 실행 후 자원을 닫아주어야 메모리 낭비가 없다.
자바 7부터는, 자원에 AutoCloseable 인터페이스를 구현시키면, 예외 발생 여부와 상관 없이 자동으로 닫아준다.
import java.util.Scanner;
public class ThrowsDemo {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("정수 입력 : ");
try {
square(in.nextLine());
} catch(NumberFormatException e) {
System.out.println("정수가 아닙니다.");
}
}
private static void square(String s) throws NumberFormatException {
// 예외가 발생하면 자신을 호출한 곳으로 예외 처리를 떠넘긴다.
// throws 문이 없었다면 여기서 try catch문을 사용했어야 했다. 그럼 코드가 지저분해진다.
int n = Integer.parseInt(s);
System.out.println(n*n);
}
}