Exception = 예외 (error와는 다르다)

[1] 자주 사용되는 Exception

  • number 의 경우 Format
  • array 의 경우 index out of bounds
  • class 의 경우 class not found
  • file 의 경우 file not found

[2] return은 함수 내에서 break 처럼 쓰일 수 있음

 

[3] 예외가 발생할 수 있는 코드를 포함한 함수를 처리할 때,

그 함수 내부에서 try-catch를 사용하지 않는 대신, throws를 던지는 방법이 있음.

그 이후, 해당 함수가 호출되는 곳에서 try-catch로 잡을 수 있음.

 

[4] 여러 세분화된 예외 클래스들을 모두 기억할 필요 없고, (Exception e) 하나로 다 잡히는 편임

try - catch - (finally) 구문 형식

            try {
                처리코드1 (예외가 나올 가능성 있는 코드)
                처리코드2 (예외가 나올 가능성 있는 코드)

            } catch(예외 클래스1) {
                예외가 나온 경우 처리

            } catch(예외 클래스2) {

            } finally {
                // finally는 생략 가능
                // try문에 진입하면 맨 마지막에 무조건 실행됨
                반드시 해야 될 뒷처리
            }

 

 

코드 예시 - 1

int[] array = { 1, 2, 3 };

System.out.println("프로그램 시작");

try {
    for (int i = 0; i < 3; i++) {
        System.out.println(array[i]);
    }
} catch(ArrayIndexOutOfBoundsException e) {
    System.out.println("배열 범위 초과");
    //e.printStackTrace();
    //System.out.println(e.getMessage());
    //return;     // <- main 함수도 void 함수이고, 여기에서 딱 튕겨나감
} catch (NumberFormatException e) {
    e.printStackTrace();
} finally {     // 문제가 있든 없든 무조건 거쳐간다
    System.out.println("무조건 처리!!!");
}

System.out.println("프로그램 끝");

 

 

코드 예시 2 - return을 제어문처럼 (break문) 사용하는 경우

function(3);
function(0);
static void function(int i) {
    if (i ==0) {
        System.out.println("i==0 이므로 다음 처리를 하지 않습니다.");
        return;
    }

    //if (i == 0) return;         // 이 함수를 빠져나가도록 함. return은 함수 계의 break문

    System.out.println("processing~~~");
}

 

 

코드 예시 3 - 함수에서 throws 를 던지고, 함수 밖에서 try-catch를 받는 경우

public class Sample1 {
    public static void main(String[] args) {
        try {
            excFunction();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("함수안의 예외");
        }
	}
    // throws -- 예외가 발생할 수 있는 코드라고 명시
    // throws가 있으면 -> 외부에서 try catch를 붙여라

    static void excFunction() throws ArrayIndexOutOfBoundsException {
        int[] array = { 1, 2, 3 };
        /*try {
            for (int i = 0; i < 4; i++) {
                System.out.println(array[i]);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }*/
        for (int i = 0; i < 4; i++) {
            System.out.println(array[i]);
        }
    }
}

 

 

대표적인 예외 처리 5가지

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • FileNotFoundException
  • NumberFormatException
  • InputMisMatchException
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Sample2 {
    public static void main(String[] args) {
        /*
            Exception : 예외
            총 5가지 정도가 대표적인 예외
         */

        // NullPointerException
        // int[] array = new int[5]; // 힙 영역에 있음
        int[] array = null; // 메모리 초기화 (힙 영역에 없음)

        try {
            System.out.println(array.length);
        } catch (NullPointerException e) {
            System.out.println("배열이 할당되어 있지 않습니다");
        }

        // ArrayIndexOutOfBoundsException
        int[] array1 = { 1, 2, 3 };
        try {
            System.out.println(array1[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("배열 범위를 초과하였습니다");
        }

        // FileNotFoundException
        File file = new File("C:\\xxx.txt");
        FileInputStream is;

        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            //throw new RuntimeException(e);
            System.out.println("파일이 존재하지 않습니다.");
        }

        // NumberFormatException
        try {
            int num = Integer.parseInt("123o3");
        } catch (NumberFormatException e) {
            System.out.println("잘못된 형식을 입력하였음.");
        }

        // InputMismatchException
        Scanner sc = new Scanner(System.in);

/*        try {
            System.out.print("number 입력 >>> ");
            int number = sc.nextInt();
            System.out.println("입력 후 실행");
        } catch (InputMismatchException e) {
            System.out.println("숫자 이외의 문자를 입력하였음");
        }*/

/*        while (true) {
            boolean b = true;
            System.out.print("숫자를 입력 >>> ");
            String numStr = sc.next();
            for (int i = 0; i < numStr.length(); i++) {
                int asc = numStr.charAt(i);     // 한글자씩 산출
                if (asc < 48 || asc > 57) {
                    b = false;
                }
            }
            if (b) break;
            System.out.println("잘못 입력하셨습니다. 다시 입력해주세요.");
        }

        int number = Integer.parseInt(numStr);
*/

        boolean b = true;
        while (true) {
            try {
                System.out.print("숫자를 입력 >>> ");
                int number = sc.nextInt();
                b = true;
                break; // 정상적으로 숫자가 입력되면 루프 종료
            } catch (InputMismatchException e) {
                System.out.println("숫자가 아닙니다");
                b = false;
                sc.next(); // 잘못된 입력을 버퍼에서 제거 - 버퍼 비우지 않으면 무한루프에 빠짐
            }
        }
    }
}

 

NullPointer? 포인터?

Java의 메모리 구조는 4 영역으로 나뉨

>> Stack , Heap , Static , Sys

 

Stack 영역에서 변수명을 저장하고 있고,

Heap 영역에서 변수명이 가리키는 데이터를 가지고 있다. (주소값이 여기에 있음)

 

그런데 만약 이런 경우를 생각해보자.

int[] array = null;

이 경우에는 heap 영역에 메모리 공간이 할당되지 않았기 때문에 array는 null을 참조하고 있게 된다.

여기에서 NullPointerException이 발생하게 되는 것임.

 

+ Recent posts