[설명]
[예제]
// Array out bound exception 발생
public class main {
public static void main(String[] args) {
int[] arr = new int[5];
for(int i = 0; i <= 5; i++) {
arr[i] = i;
}
}
}
// 에러나는 이유?
/*
arr의 범위는 0 ~ 4 총 5개의 인덱스를 가지고 있습니다
arr[5]는 존재하지 않기 때문에 인덱스 범위를 초과한 것입니다
그래서 ArrayIndexOutBoundsException이 발생합니다
*/
[설명]
[예제]
// Array out bound exception 예외처리
public class main {
public static void main(String[] args) {
try {
int[] arr = new int[5];
for(int i = 0; i <= 5; i++) {
arr[i] = i;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("-ArrayIndexOutOfBoundsException 발생-");
System.out.println("현재 코드를 체크해주세요!");
} finally {
System.out.println("예외처리 코드가 오류없이 진행 완료되었습니다.");
}
}
}
}
[설명]
[예제]
// **EmptyStackException 발생
StackPopException isEmpty = new StackPopException();
isEmpty.push(10);
isEmpty.push(20);**
System.out.println("pop : " + isEmpty.pop3());
System.out.println("pop : " + isEmpty.pop3());
System.out.println("pop : " + isEmpty.pop3());
// **EmptyStackException 결과
// 10
// 20
// EmptyStackException 발생합니다**
[설명]
[예제]
// **EmptyStackException 처리
public class main {
// throw new RuntimeException(); 을 사용함
public int pop() {
if(isEmpty()) throw new RuntimeException("스택이 비었습니다.");
return this.arr[--pointer];
}
}
StackPopException isEmpty = new StackPopException();
isEmpty.push(10);
isEmpty.push(20);**
System.out.println("pop : " + isEmpty.pop3());
System.out.println("pop : " + isEmpty.pop3());
System.out.println("pop : " + isEmpty.pop3());
// **EmptyStackException 결과
// 20
// 10
// Exception in thread "main"
// java.lang.RuntimeException: 스택이 비었습니다.**