본문 바로가기

프로그래밍 언어/Java

예외처리(Exception)

예외처리는 프로그램 실행 중 발생할 오류를 개발자가 미리 대처하는 코드다. 

 

오류(Error)는 프로그램 실행 과정에서 시스템적으로 비정상적인 상황을 의미하며 크게 컴파일 과정에서 발생하는 Complie Error, 실행 중 발생하는 Runtime Error 로 나뉘며 예외처리는 이 중에서도 예측 가능한 Runtime Error 를 잡는 행위이다. 

 

Java 에서는 예외처리 구문은 다음과 같은 구조로 이루어져있다. 

 

 

1. 일반적인 try-catch

try {

}catch (Exception e) {

}

 

2. 다중 try-catch

try {

}catch (NullPointerException e1) {

}catch (ArrayIndexOutOfBoundsException e2) {
    
}

 

3. 중복 try-catch

try {

}catch (NullPointerException | ArrayIndexOutOfBoundsException e) {

}

 

 

Thorws/Throw

 

1. Throws: 메소드 자체 예외처리 시

public void method() throws NullPointerException{

}

 

2. Throw: 특정 Excption 을 Call 하는 경우

public static void method(int A){
        if(A > 0) throw new NullPointerException("sad");
}

 

 

Custom Exception

public class MyCustomException extends Exception{
    public MyCustomException(String message){
        super(message);
    }
}
public void main(String[] args) {
        try {
            method(1);
        }catch (MyCustomException e) {

        }
    }

public static void method(int A) throws MyCustomException {
	if(A > 0) throw new MyCustomException("에러발생");
}