본문 바로가기
Framwork/Java기초

Chapter 12. 예외 처리

by 김엉배 2023. 8. 15.
728x90
반응형

목차

1. 프로그램 오류와 예외 처리
2. try ~ catch 구문으로 예외 처리하기
3. 예외 생성하기

 

 

1.  프로그램 오류와 예외 처리


- 프로그램을 작성하고 실행 시키는 과정에서 크게 두 종류 에러가 발생할 수 있다.

  • 자바 에러 
    - 컴파일 에러: 컴파일 시에 발생하는 에러(잘못된 문법 기술)
    - 런타임 에러: 프로그램 실행 시에 발생하는 에러
  • 런타임 에러
    - 에러(error): 프로그램 코드로 수습될 수 없음(예: 메모리 부족 등)
    - 예외(exception): 프로그램 코드로 수습할 수 있음(예: 배열 인덱스 오류 등)

- 자바의 예외 처리 방법

  • try ~ catch ~ finally 구문 이용하기
  • throws 이용하기

 

 

 

2.  try ~ catch 구문으로 예외 처리


  • ex) 0으로 나누는 경우에 발생하는 예외
package exceptiontest1;

public class code193 {
  public static void main(String[] args) {
    int a = 5, b = 0, c;
    System.out.println("c: " + c);
  }
}
---------------------------------------------
결과
Exception in thread "main" java.lang.ArithmeticException: /by zero
at exceptiontest1.code193.main(code193.java:7)

// ArithmeticException이 발생.
// by zero: 0으로 나누어서 예외가 발생함.

 

  • ex) 배열의 인데스 범위를 벗어나는 경우에 발생하는 예외(배열의 인덱스를 잘못 적는 경우)
package exceptiontest2;

public class code194 {
  public static void main(String[] args) {
    int n[] = {1, 3, 5, 6, 10};
    for(int i=0; i<=5; i++) { // 인덱스 5가 없다.
      System.out.println("n[" +i+ "]= " +n[i]);
    }
  }
}
---------------------------------------------------
결과
n[0] = 1
n[1] = 3
n[2] = 5
n[3] = 6
n[4] = 10

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5 at exceptiontest2.code194.main(code194.java:8)

//ArrayIndexOutOfBoundsException이 발생.
//Index 5 out of: 배열 n에 인덱스 5가 없음.

 

  • try ~ catch ~ finally를 이용해 예외 처리
try {
	//예외가 발생할 가능성이 있는 코드
} catch (Exception1 e1) {
	//Exception1 발생했을 경우, 이를 처리하기 위한 코드
}
....
finally {
	//무조건 수행되는 코드
}

 

  • ex) 0으로 나누는 경우에 발생하는 예외처리
public class code195 {
  public static main(String[] args) {
    int a = 5, b = 0, c;
    try {
      c = a/b; // 에러가 발생할 가능성이 있는 코드
      System.out.println("c: " + c); // 위의 코드에 영향받는 코드
    }
    catch(ArithmeticException e) { // try 블록 안에서 ArithmeticException 발생할 수 있다.
      System.out.println("0으로 나눌 수 없습니다.");
    }
  }
}
------------------------------
결과
0으로 나눌 수 없습니다.

 

  • ex) 배열 인덱스 예외처리
public class code196 {
  public static void main(String[] args) {
    int n[] = {1, 3, 5, 6, 10};
    int i = 0;
    try {
      for(i=0;i<=5;i++) {
        System.out.println("n[" +i+ "]=" + n[i]);
      }
    }
    catch(ArrayIndexOutOfBoundsException e) {
      System.out.println(i + "는 없는 인덱스입니다.");
    }
  }
}
---------------------------------------------------
결과
n[0]=1
n[1]=3
n[2]=5
n[3]=6
n[4]=10
5는 없는 인덱스입니다.

 

  • Trowable 클래스 메소드
메소드 설명
String getMessage() 예외에 대한 설명을 반환함.
void printStackTrace() 발생한 예외에 대한 정보를 반환함.

// 비교 1
public static void main(String[] args) {
	int A[] = new int[5];
    try {
    	A[7] = 100;
    }
    catch(ArrayIndexOutOfBoundsException e) {
    	System.out.println("Exception message: " +e.getMessage());
    }
}
---------------------------------------
결과1
Exception message: index 7 out of bounds for length 5

// 비교 2
public static void main(String[] args) {
	int A[] = new int[5];
    try {
    	A[7] = 100;
    }
    catch(ArrayIndexOutOfBoundsException e) {
		e.printStackTrace(); // 에러 메시지가 그대로 모두 출력
    }
}
---------------------------------------
결과2
java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
at.exceptiontest5.code203.main(code203.java:8)

 

  • throws를 이용하여 예외 처리하기
// makeArray() 메소드에서 예외가 발생하는데 예외처리 x
// 대신 thriws 구문을 이용해 makeArray() 메소드를 호출하는 메소드에게
// 예외 처리를 하도록 함.

public static void makeArray() throw ArrayIndexOutOfBoundsException {
	int A[] = new int[3];
    A[0] = 10;
    A[1] = 20;
    A[2] = 30;
    A[3] = 40;
    A[4] = 50;
}

public static void main(String[] args) {
	System.out.println("main starts");
    try {
    	// makeArray()에서 예외가 발생하면 여기에서 처리
    	makeArray();
    } catch(ArrayIndexOutOfBoundsException e) {
    	System.out.println("Exception message: " + e.getMessage());
    }
    System.out.println("main ends");
}
-----------------------------------------------
결과
main starts
Exception message: Index 3 out of bounds for length 3
main ends

 

 

3.  예외 생성하기


// Exception 클래스를 상속받는 클래스 생성
class MyException extends Exception {
	int x;
    MyException(int x) { //사용자가 만든 예외 클래스.
    	this.x = x;
    }
    public String toString() {
    	return "I am " +x+ " in MyException class";
    }
}
public class code207 {
	public static void main(String[] args) {
    	// me는 예외 객체 참조 변수.
    	MyException me = new MyException(10);
        try {
        	System.out.println("before throw MyException");
            throw me; // 예외를 발생시킴
        }
        catch(MyException e) {
        	Sytem.out.println(e);
        }
        System.out.println("main ends");
    }
}
----------------------------------------------
결과
before throw MyException
I am 10 in MyException class
main ends

 

  • 사용이 많은 예외 목록
예외명 의미
ArrayIndexOutOfBoundsException 배열 범위를 벗어남.
ArihmeticException 연산에 문제가 있음(예: 0으로 나누기)
FileNotFoundException 존재하지 않는 파일에 접근하기
NullPointerException 인스턴스를 제대로 생성하지 않음
ClassNotFoundException 존재하지 않은 클래스임
NumberFormatException 문자열을 수치로 전환활 떄 발생함
728x90
반응형