1. NullPointerException : 객체 참조가 없는 상태 ( 객체가 없는 상태에서 객체를 사용하려 할 때 발생 )
public class NullPointerException02 {
public static void main(String[] args) {
try {
String str = null; // 객체가 아직 생성되지 않은 상태에서
System.out.println(str.toString()); // 주소값이 없는데 toStirng 호출하므로 오류 !
} catch(NullPointerException e) {
System.out.println("데이터가 들어 있지 않습니다");
System.out.println("예외메시지 : " + e);
}
System.out.println("끝까지 실행 완료");
}
}
출력결과 )
2. ArrayIndexOutOfBoundsException : 배열에서 인덱스 범위를 초과할 경우 발생
public class ArrayIndexOutOfBounds03 {
public static void main(String[] args) {
String str[] = {"a","b","c"};
try {
str [4] = "d";
} catch(ArrayIndexOutOfBoundsException abe) {
System.out.println("배열의 범위를 넘었습니다. index는" + (str.length-1) + "까지만 사용가능");
System.out.println(abe);
}
System.out.println(Arrays.toString(str)); // 오버라이딩
}
}
출력결과 )
3. NumberFormatException : 문자열이 나타내는 숫자와 일치하지 않는 타입의 숫자로 변환 시 발생
public class NumberFormat04 {
public static void main(String[] args) {
String strNum[] = {"23","17","123abc","3.141592"};
for(String num : strNum) {
int result = Integer.parseInt(num); // String을 int형으로 변경
System.out.println("숫자로 변환된 값 : " + result);
}
}
출력결과 )
예외처리 후 !
public class NumberFormat04 {
public static void main(String[] args) {
String strNum[] = {"23","17","123abc","3.141592"};
int i = 0;
try {
for (i=0; i<strNum.length; i++) {
int result = Integer.parseInt(strNum[i]);
System.out.println("숫자로 변환된 값 : " + result); }
} catch(NumberFormatException ne) {
System.out.println("숫자로 변경 불가");
System.out.println("'" + strNum[i] + "'는 숫자로 변경불가");
}
}
}
출력결과 )
'Java' 카테고리의 다른 글
Java문법) 예외처리 -4 (throw와 throws) (0) | 2023.11.01 |
---|---|
Java문법) 예외처리 -3 (ClassCastException, InputMismatchException) (0) | 2023.11.01 |
Java문법) 예외처리 -1 (0) | 2023.10.31 |
Java문법) final 키워드 (0) | 2023.10.30 |
Java 문법) 가변인자 (0) | 2023.10.27 |