[Java] 3. 예외 처리

seungwon·2021년 6월 12일
0

Java

목록 보기
3/5

목차

  • 컴파일 오류 vs 예외
  • 예외처리
  • 예외 클래스
  • 예외처리 예시 코드

컴파일 오류 vs 예외

Exception


Exception : Check의 주체는 컴파일러

  1. Checked Exception : 컴파일에러가 남
  2. Unchecked Exception : 실행됨, 실행되다가 죽음 ==> 예외처리 필요!!

컴파일

문법에 맞지 않게 작성된 코드 : 실행이 안됨

예외 (Runtime Error)

실행 중에 발생한 오류 (오동작이나 결과에 악영향을 미칠 수 있음)

ex)

  • 정수를 0 으로 나누는 경우
  • 배열크기보다 큰 인덱스로 배열의 원소를 접근
  • 존재하지 않는 파일을 읽으려고 하는 경우

자바에서 예외 처리

예외 발생 -> 자바 플랫폼 인지 -> 응용프로그램에서 전달 -> 응용프로그램이 예외를 처리하지 않으면 강제 종료


예외처리

try-catch(-finally) 문

try{
      예외가 발생할 가능성이 있는 실행문 (try 블록)
}
catch(처리할 예외 타입 선언){ // catch 블록은 여러개 올 수 있음
      예외 처리문(catch 블록)
finally{ // 예외 처리 때문에 추가된 코드
      예외 발생 여부와 상관없이 무조건 실행되는 문장

  • catch문에 return문이 있어도 finally{..} 를 실행 후에 catch 블록내의 리턴문 수행
  • catch문이 여러개일 때 중복된 부분 / 예외발생과 상관없이 균일하게 하는 작업

}

속도는 조금 느려 실시간 반응 프로그램을 만드는데는 사용하지 않음

예외 클래스

  • 자주 발생하는 예외


예외처리 예시 코드

  • 0으로 나눌 때 (ArithmeticException)
import java.util.Scanner;

public class DevideByZeroHandling {
	public static void main(String[] args) { 
    	Scanner scanner = new Scanner(System.in);

		while(true) {
			System.out.print("나뉨수를 입력하시오:");
			int dividend = scanner.nextInt(); // 나뉨수 입력 
            System.out.print("나눗수를 입력하시오:");
			int divisor = scanner.nextInt(); // 나눗수 입력
			try{
				System.out.println(dividend + "를 " + divisor + 
                "로 나누면 몫은 " + dividend/divisor + "입니다.");
				break; // 정상적인 나누기 완료 후 while 벗어나기
			}
            // ArithmeticException 예외 처리 코드
			catch(ArithmeticException e) { // class 명 = ArithmeticException 
            	// e.printStacktrace() 자주 사용됨 : 예외 발생 함수부터 trace를 출력
				System.out.println("0으로 나눌 수 없습니다! 다시 입력하세요");
            }
		}
		scanner.close();
	}
}
  • 범위를 벗어난 배열의 접근 (ArrayIndexOutOfBoundsException)
public class ArrayException {
	public static void main (String[] args) {
    	int[] intArray = new int[5];    
        intArray[0] = 0;
		try {
			for (int i=0; i<5; i++) { 
            	intArray[i+1] = i+1 + intArray[i];
				System.out.println("intArray["+i+"]"+"="+intArray[i]); 
        	}
		}
		catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("배열의 인덱스가 범위를 벗어났습니다."); 
       }
	} 
}
  • 입력 오류 시 발생하는 예외 (InputMismatchException)
import java.util.Scanner;
import java.util.InputMismatchException;

public class InputException {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in); 
		System.out.println("정수 3개를 입력하세요"); 
		int sum=0, n=0;
		
		for(int i=0; i<3; i++) {
			System.out.print(i+">>");
			try {
				n = scanner.nextInt(); // 정수 입력 -> 사용자가 문자를 입력하면 예외 발생
			}
			catch(InputMismatchException e) {
				System.out.println("정수가 아닙니다. 다시 입력하세요!"); 
				scanner.next(); // 입력 스트림에 있는 정수가 아닌 토큰을 버린다. 
				i--;// 인덱스가 증가하지 않도록 미리 감소
				continue; // 다음 루프
			}
			sum += n; // 합하기 
		}
		System.out.println("합은 " + sum);
		scanner.close(); 
	}
}
  • 정수가 아닌 문자열을 정수로 변환할 때 예외 발생(NumberFormatException)
public class NumException {
	public static void main (String[] args) {
		String[] stringNumber = {"23", "12", "3.141592", "998"};
		
		int i=0;
		try {
			for (i=0; i<stringNumber.length; i++){
				int j = Integer.parseInt(stringNumber[i]); 
				//“3.141592”를 정수로 변환할 때 NumberFormatException 예외 발생
				// 사후처리(예외처리)가 아닌 if문으로 예방하려 하면 너무 복잡, 따질게 많음
				System.out.println("숫자로 변환된 값은 " + j); 
			}
		}
		catch (NumberFormatException e) {
			System.out.println(stringNumber[i] + "는 정수로 변환할 수 없습니다."); 
		}
	} 
}

참고 자료 (사진 출처)

명품 Java Programming(황기태, 김효수 저)

2개의 댓글

comment-user-thumbnail
2023년 2월 10일
답글 달기
comment-user-thumbnail
2023년 5월 19일

Yes, I agree with you completely. You can't have a successful online presence for your organisation without top quality content, which is why technical writing free games is so crucial.

답글 달기