목차

  1. 예외 처리
  2. 예외 클래스
  3. 예외 던지기

1. 예외 처리

2. 예외 클래스

3. 예외 던지기

실행 예외 (런타임)

int num1 = 1;
int num2 = 0;

try {
	int result = num1 / num2;  // 0으로 나누기 예외 발생
} catch (ArithmeticException e) {
	e.printStackTrace();
}

int[] arr = {1,2,3,4,5};

try {
	for(int i=0; i<=5; i++) {
		System.out.print(arr[i] + " ");  // 배열 인덱스 초과
	}
} catch (ArrayIndexOutOfBoundsException e) {
	e.printStackTrace();
}

Animal animal = null;

try {
	animal.move();  // NullPointerException
} catch (NullPointerException e) {
	e.printStackTrace();
}

잘못된 캐스팅 예외

Animal a1 = new Tiger();
Animal a2 = new Eagle();

try {
	Shark shark = (Shark) a2;  // ClassCastException
	shark.move();
} catch (ClassCastException e) {
	e.printStackTrace();
}

일반 예외 (컴파일 예외)