예외 발생 - try-catch 문

양혜정·2024년 1월 20일
0

Begin_java

목록 보기
9/71

try-catch 문

- try { } 내에서 예외가 발생한 경우

발생한 예외와 일치하는 catch 블럭으로 이동
일치하는 catch 블럭 내 문장을 수행하고 try-catch 문을 나와 프로그램 진행

- try { } 내에서 예외가 발생하지 않은 경우

catch 블럭을 건너뛰어서 진행

Scanner sc = new Scanner(System.in);
System.out.print("정수를 입력하세요 => ");

try{
	int inputNum = sc.nextInt(0;
    sc.nextLine();
    System.out.println("입력한 정수 : " + inputNum);

} catch(InputMismatchException e) {	// InputMismatchException : 정수를 입력해야 하는데 문자를 입력한 경우 예외 발생
		System.out.println(">> 경고 : 정수만 입력하세요!! <<");
      	e.printStackTrace();	// 오류 주소 출력
     	 }
sc.close();

예외발생 종류

  • InputMismatchException
    정수를 입력해야 하는데 문자를 입력

  • ArithmeticException
    정수를 0으로 나눈 경우

  • NullPointerException
    null reference 를 참조한 경우

  • ArrayIndexOutOfBoundException
    배열의 범위를 벗어나서 접근

  • FileNotFoundException
    파일을 찾을 수 없는 경우

  • NumberFormatException
    문자를 숫자로 변환하는 경우

  • ClassNotFoundException
    클래스 로딩에 실패한 경우


try-catch 응용

1. Byte 타입이 아닌 다른 타입들도 경고를 주려고 할 때,

-> Ex1) printStackTrace() 와 getMessage() 이용

e.printStackTrace() : 에러위치를 알려준다.
e.getMessage : 에러 입력값을 알려준다.

try{
	System.out.print("국어 : ");
    byte kor = Byte.parseByte(sc.nextLine());
    if(!sj.check_jumsu(kor)){
    		sc.close();
            return;		// return 을 만나면 해당 메소드는 종료된다.
            }
      else{
      		sj.kor = kor;
    } catch(NumberFormatException e) {
    			e.printStackTrace()						// 에러위치 알려줌.
                System.out.println(e.getMessage);		// 에러 입력값 알려줌
                }

-> Ex2) 초기화를 이용

String input_str = "";
try{
	System.out.print("국어 : ");
    input_str = sc.nextLine();
    byte kor = Byte.parseByte(input_str);
    if(!sj.check_jumsu(kor)){
    		sc.close();
            return;		// return 을 만나면 해당 메소드는 종료된다.
            }
      else{
      		sj.kor = kor;
    } catch(NumberFormatException e) {
    			e.printStackTrace()						// 에러위치 알려줌.
                System.out.println(e.getMessage);		// 에러 입력값 알려줌
                System.out.println("입력하신 " + input_str + " 는 올바른 데이터가 아닙니다");
            }

2. 성적과 나이에 대해 오류 추출

-> Ex1) try-catch 문을 2회 사용

try{ ~~~
    if(!sj.check_jumsu(kor)){
            sc.close();
            return;
       } else {
            sj.kor = kor;
       }
} catch (NumberFormatException e) {
				e.printStackTrace();
                System.out.println(e.getMessage());
       }	// try-catch 문 종료
      
System.out.println("나이 : ");
try{
	input_str = sc.nextLine();
    short age = Short.parseShort(input_str);
    if(!sj.check_age(age)) {
    		sc.close();
            return;
       }
       ~~~
} catch (NumberFormatException e) {
	System.out.println("입력하신 " + input_str + "는 올바른 데이터가 아닙니다.\n"
    				+ "[ 나이에 대한 경고 ] 나이는 20살 이상만 입력해주세요");

-> Ex2) 초기화 값 지정하여 사용

int status = 0;	// 점수를 입력해주는 상태 : 1
				// 나이를 입력해주는 상태 : 2
      
try{
	status = 1;
    System.out.print("국어 점수 : ");
    input_str = sc.nextLine();
    byte kor = Byte.parseByte(input_str);
    
    if(!sj.check_jumsu(kor)) {
    		sc.close();
            return;
    } else {
    		sj.kor = kor;
            }
    
    status = 2;
    System.out.print("나이 : ");
    input_str = sc.nextLine();
    short age = Short.parseShort(input_str);
    
    if(!sj.check_age(age)) {
    		sc.close();
            return;
    } else {
    		sj.age = age;
            }
} catch (NumberFormatException e) {
			System.out.println("입력하신 " + input_str + "는 올바른 데이터가 아닙니다.\n");
            if(status == 1) {	// 점수를 입력한 상태
            	System.out.println("[ 점수에 대한 경고 ] 점수는 0 ~ 100 까지의 정수만 입력하세요.");
            } else {			// 나이를 입력한 상태
            		System.out.println("[ 나이에 대한 경고 ] 나이는 20살 이상만 입력해주세요");
       			}	// if-else 종료
	} 	// try-catch 문 종료
sc.close();

정리

my.day03.c.scanner -> Main_scanner_2
my.day04.b.sungjuk -> Main_Sungjuk

0개의 댓글

관련 채용 정보