실행 예외는 자바 컴파일러가 체크하지 않기 때문에 개발자가 직접 코드를 작성해줘야 한다.
자주 발생되는 실행 예외 목록)
1. NullPointerException
객체 참조가 없는 상태, 즉 null 값을 갖는 참조 변수로 객체 접근 연산자인 도트(.)를 사용했을 때 발생
public class NullPointerExceptionExample {
public static void main(String[] args) {
String data = null;
System.out.println(data.toString());
}
}
2. ArrayIndexOutOfBoundsException
배열에서 인덱스 범위를 초과하여 사용할 경우 발생 (또는 해당 인덱스의 데이터가 없을 경우에도 발생)
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
// 배열값을 읽기 전에 배열의 길이를 먼저 조사한다.
// 실행 매개값이 없거나 부족할 경우 조건문을 이용!
if(args.length==2) {
String data1 = args[0];
String data2 = args[1];
System.out.println("args[0]: " + data1);
System.out.println("args[1]: " + data2);
} else {
System.out.println("[실행 방법]");
System.out.print("java ArrayIndexOutOfBoundsExceptionExample");
System.out.println(" 값1 값2");
}
}
}
3. NumberFormatException
문자열을 숫자열로 변경할 때, 문자열에 숫자로 변환될 수 없는 문자가 포함된 경우 발생
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String data1 = "100";
String data2 = "a100";
int value1 = Integer.parseInt(data1);
int value2 = Integer.parseInt(data2); // 예외 발생
}
}
4. ClassCastException
강제 타입 변환(Casting)이 되지 않을 경우 발생
public class ClassCastExceptionExample {
public static void main(String[] args) {
Animal animal = new Dog();
Dog dog = (Dog) animal;
Cat cat = (Cat) animal; // animal은 Dog객체이므로 Cat으로 강제타입변환 불가
}
}
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
ClassCastException을 발생시키지 않으려면 타입 변환 전에
타입 변환이 가능한지 instanceof 연산자로 확인하는 것이 좋다.
public class ClassCastExceptionExample2 {
public static void main(String[] args) {
Dog dog = new Dog();
changeDog(dog);
Cat cat = new Cat();
changeDog(cat);
}
public static void changeDog(Animal animal) {
// 매개값의 타입 확인
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
System.out.println("Dog로 변환 하였습니다.");
} else {
System.out.println("Dog로 변환이 불가능합니다.");
}
}
}
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
'개발 공부 > JAVA' 카테고리의 다른 글
다중 catch / 멀티 catch (0) | 2021.06.18 |
---|---|
예외 처리 코드(try-catch-finally 블록) (0) | 2021.06.18 |
예외(Exception) (0) | 2021.06.18 |
디폴트 메소드와 인터페이스 확장(java8부터 허용) (0) | 2021.06.11 |
인터페이스 상속 (0) | 2021.06.11 |