[Java] 예외 처리

rara_kim·2022년 6월 13일
0

Java

목록 보기
14/39

예외처리(Exception Handling)

예외

정상적이지 않은 Case를 두고 예외라고 한다.
ex) 0으로 나누기, 배열의 인덱스 초과, 없는 파일 열기 등...


예외 처리(Exception Handling)

  • 정상적이지 않은 Case에 대한 적잘한 처리 방법
  • try/catch문으로 예외 처리
try{
	예외가 발생할 수도 있는 코드
} catch(예외 case1) {
	예외 발생 시 실행할 코드
} catch(예외 case2) {
	예외를 여러개 등록해서 처리 가능, 혹은 상위 예외로 처리하는 것도 가능
}


//try-catch 사용예시
    try {
        int a = 5 / 0 ;
    } catch (ArithmeticException e) {     //매개변수로 구체적인 예외를 넣어주는 것이 좋음
        System.out.println(e);
    }

finally

예외 발생 여부와 관계없이 항상 실행되는 부분

try {
    int a = 5 / 0;
} catch (ArithmeticException e) {
    System.out.println(e);
} finally {
    System.out.println("테스트 종료");        //예외가 있어도 없어도 항상 실행되는 내용
}

throw, throws

1️⃣throw
예외를 발생시킴

public static boolean checkTenWithException(int ten) {
    try {
        if (ten != 10) {
            throw new NotTenException();
        }
    } catch (NotTenException e) {
        System.out.println(e);
        return false;
    }
    return true;
}

2️⃣throws

  • 예외를 전가시킴
  • 메소드명 옆에 전가시킬 예외명을 써준다.
public static boolean checkTenWithThrows (int ten) throws NotTenException {
    if	(ten % 3 == 0) {
    	return true;
    }
    return false;
}
profile
느리더라도 꾸준하게

0개의 댓글