Java

Java catch

승모근뭉치 2023. 1. 29. 02:14

프로젝트 내 src 내 javabasic 패키지 내 Ex3Exception.java

package javabasic;

import java.util.Scanner;

public class Ex3Exception {

	public static void process() throws NumberFormatException, ArithmeticException {
		Scanner sc = new Scanner(System.in);
		int su1, su2;
		System.out.println("두개의 숫자를 입력하세요");
		su1 = Integer.parseInt(sc.nextLine());
		su2 = Integer.parseInt(sc.nextLine());

		int div = su1 / su2;
		System.out.printf("%d / %d = %d\n", su1, su2, div);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			process();
		} catch (ArithmeticException e) {
			System.out.println("0으로 나누면 안돼요:" + e.getMessage());
		} catch (NumberFormatException e) {
			System.out.println("문자가 들어있어요:" + e.getMessage());
		} finally {
			System.out.println("무조건 실행");
		}

		System.out.println("** 정상 종료 **");
	}

}

실행 결과

두개의 숫자를 입력하세요
2
3
2 / 3 = 0
무조건 실행
** 정상 종료 **

스캐너로 두개의 숫자를 입력할 때 구분자를 엔터로 주지 않고 탭으로 주었을 때 위의 코드에서는 nextLine() 을 쓰기때문에 오류가 난다.

두개의 숫자를 입력하세요
3	2
문자가 들어있어요:For input string: "3	2"
무조건 실행
** 정상 종료 **
두개의 숫자를 입력하세요
3
0
0으로 나누면 안돼요:/ by zero
무조건 실행
** 정상 종료 **