1. 범위를 벗어난 배열의 접근
오류 메세지
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
코드
public class DEMO {
public static void main(String[] args) {
int [] array = { 0, 1, 2, };
System.out.println(array[3]);
}
}
배열의 크기가 3이고 배열이 0부터 시작하기 때문에 배열 3칸은 없음.
2. 0으로 나눌때 발생하는 ArithmeticException 예외
public class Demo2 {
public static void main(String[] args) {
int [] aa = new int[3];
try {
aa[2] = 100/0;
aa[3] = 100;
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열 첨자가 배열 크기보다 커요 ~~");
} catch (ArithmeticException e) {
System.out.println("0으로 나누는 등의 오류에요~~");
} finally {
System.out.println("이 부분은 무조건 나와요 ~~");
}
}
}
public class Demo3 {
public static void main(String[] args) {
int a = 100, b = 0;
int result;
try {
result = a / b;
} catch (ArithmeticException e) {
System.out.print("발생 오류 ==>");
System.out.println(e.getMessage());
}
}
}
결과
발생 오류 ==>/ by zero
3. 예외발생으로 프로그램이 강제 종료되는 경우
오류 메세지 : Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException
package test01;
public class Demo3 {
public static void main(String[] args) {
Thread.sleep(100);
}
}
4. 예외 잡아 처리하기 (범위를 벗어난 배열의 접근 )
try {
예외가 발생할 수 있는 실행문;
} catch (예외클래스 1 | 예외 클래스 2 변수) {
핸들러;
}
public class Demo3 {
public static void main(String[] args) {
int [] array = { 0 , 1, 2, };
try {
System.out.println("마지막 원소 => " + array[3]);
System.out.println("첫 번째 원소 => " + array[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("원소가 존재하지 않습니다. ");
}
System.out.println("어이쿠!!");
}
}
ArrayIndexOutOfBoundsException : 배열, 벡터 등에서 범위를 벗어난 인덱스를 사용할 때 발생한다.
결과
원소가 존재하지 않습니다.
어이쿠!!
'JAVA > 문법' 카테고리의 다른 글
[JAVA] 인터페이스 구현 (0) | 2020.01.04 |
---|---|
[JAVA] 추상클래스 (0) | 2020.01.04 |
[JAVA] 클래스 (0) | 2019.12.22 |
[JAVA] 배열 2 (0) | 2019.12.15 |
[JAVA] 배열 (0) | 2019.12.15 |