본문 바로가기

IT/Java

14_자바 예외 : 에러(Error)와 예외(Exception), 자바 예외의 종류

01. 에러와 예외

- 에러 : 컴퓨터 하드웨어의 오동작 또는 고장으로 인해 응용프로그램 실행 오류가 발생하는 것. JVM 실행에 문제가 생겨 실행 불능 상태가 됨. 대처 불가

- 예외 : 사용자의 잘못된 조작 또는 개발자의 잘못된 코딩으로 인해 발생하는 프로그램 오류. 예외 처리를 통해 프로그램이 종료되지 않도록 대처 가능

 

02. 예외분류

03. 실행예외

일반예외 : 자바 소스를 컴파일하는 과정에서 예외 처리 코드가 필요한지 검사한다.

실행예외 : 컴파일러가 체크를 하지 않기 때문에 개발자의 경험에 의해서 예외 처리 코드를 삽입한다.

따라서, 실행 예외의 종류, 그리고 언제 그러한 예외가 발생하는지 평소에 잘 알아두는 것이 중요하다.

다음은 자바에서 가장 자주 볼 수 있는 실행예외들의 예시이다.

 

1) NullPointerException

- 객체 참조가 없는 null 상태에서 객체를 사용하려고 할 때 발생하는 예외

1
2
3
4
5
6
7
8
9
10
11
12
public class NullPointerExceptionExample {
    public static void main(String[] args) {
        String data = null;
        System.out.println(data.toString());
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

2) ArrayIndexOutOfBoundsException

- 배열에서 인덱스의 범위를 초과하여 사용하려고 할 때 발생한다.

1
2
3
4
5
6
7
8
9
10
public class ArrayIndexOutOfBoundsException {
    public static void main(String[] args) {
            
        String[] strings = new String[2];
        for(int i=0; i <3; i++) {
            strings[i] = "data"+(i+1);
            System.out.println(strings[i]);
        }
        
    }
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

위의 코드 for문 내부의 i값 범위가 잘못 되었다.

이러한 실수를 막기 위해서는 숫자를 직접 넣기 보다는 아래와 같이 배열명.length 라고 작성해주는 것이 좋다.

1
2
3
4
5
6
7
8
9
10
public class ArrayIndexOutOfBoundsException {
    public static void main(String[] args) {
            
        String[] strings = new String[2];
        for(int i=0; i <strings.length; i++) {
            strings[i] = "data"+(i+1);
            System.out.println(strings[i]);
        }
        
    }
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

3) NumberFormatException

- 개발을 하다 보면 문자열을 숫자형 데이터로 변경해야 할 경우가 있다.

- 이 때 숫자로 변환할 수 없는 값이 들어있는 경우 넘버포맷익셉션이 발생한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
        
        int result = value1 + value2;
        System.out.println(data1 + "+" + data2 + "=" + result);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

4) ClassCastException

- 상하위 관계에 있는 클래스, 또는 구현클래스와 인터페이스 관계가 아닐 때 억지로 타입변환을 시도할 때 발생한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package ex01_runtime;
 
public class ClassCastExceptionExample {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Cat cat = (Cat) dog;        
    }
 
}    //end class
 
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

따라서 아래와 같이 instanceof 연산자를 활용하여 검사를 먼저 하고, 나중에 타입변환을 하도록 코드를 짜는 것이 좋다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package ex01_runtime;
 
public class ClassCastExceptionExample {
    public static void main(String[] args) {
 
        Animal dog = new Dog();
        if(dog instanceof Cat) {
        Cat cat = (Cat) dog;
        } else {
            System.out.println("타입 변환이 불가능합니다.");
        }
        
    }
 
}    //end class
 
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter