728x90
예외 순위는 Exception>>>>>>나머지. 즉, Exception은 가장 나중에 작성해야함
package test12;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionTest4 {
public static void main(String[] args) {
// 2개의 정수를 입력받아 사칙연산을 수행하는 프로그램 작성
// 1. 정수값이 아닌 다른 자료형이 입력될 경우 예외 처리 -> InputMismatchException
// 2. 0으로 나누는 경우의 예외 처리 -> ArithmeticException
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.println("정수1을 입력");
int n1 = sc.nextInt();
System.out.println("정수2을 입력");
int n2 = sc.nextInt();
System.out.println("정수1 + 정수2 = " + (n1 + n2));
System.out.println("정수1 - 정수2 = " + (n1 - n2));
System.out.println("정수1 * 정수2 = " + (n1 * n2));
System.out.println("정수1 / 정수2 = " + ((double) n1 / (double) n2));
} catch (InputMismatchException e) {
System.out.println("숫자가 아닙니다.");
System.out.println(sc.next() + "숫자가 아니므로 무시합니다.");
} catch (ArithmeticException e) {
System.out.println("정수2는 0이 될 수 없습니다.");
} catch (Exception e) {
System.out.println("런타임 오류 발생");
} finally {
try {
System.out.println("한 번 더 실행하시겠습니까? 0.아니요, 1.예");
int re = sc.nextInt();
if (re == 0) {
System.out.println("프로그램을 종료합니다.");
break;
}
}
catch (InputMismatchException e) {
System.out.println("숫자가 아닙니다.");
System.out.println(sc.next() + "숫자가 아니므로 무시합니다.");
} catch (ArithmeticException e) {
System.out.println("정수2는 0이 될 수 없습니다.");
} catch (Exception e) {
System.out.println("런타임 오류 발생");
}
}
}
}
}
try catch문안에 try catch가 들어갈 수 있음
예외처리 미루기 throws
예외를 해당 메소드에서 처리하지 않고 미룬 후 메소드 호출하여 사용하는 부분에서 예외를 처리하는 방법
package test12;
public class ExceptionTest5 {
// throws : 현재 메소드가 예외를 처리하지 않고 자신을 호출한 메소드쪽으로 예외처리를 떠넘김
// 현재 메소드가 예외를 처리하지 않고 자신을 호출한 메소드쪽으로 예외 처리를 떠넘김
// 메소드의 매개변수 뒤에 throws ArithmeticException 예외 클래스를 지정
public static int divide(int n1, int n2) throws ArithmeticException {
int result = n1 / n2;
return result;
}
public static void main(String[] args) {
int n1 = 10;
int n2 = 0;
try {
int result = divide(n1, n2);
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다.");
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("기타 예외 발생");
System.out.println(e.getMessage());
} finally {
System.out.println("예외가 발생 유무에 상관없이 반드시 수행됨");
}
}
}
사용자 정의 예외
예외 처리 클래스 이외에 개발하는 프로그램에 따라 다양한 예외 상황이 발생할 수 있음.
조건을 체크하는 작업을 자바 프로그램에서 한다면 예외 클래스를 직접 만들어 예외를 발생시키고
예외 처리 코드를 구현할 수 있음.
사용자 정의 예외 클래스를 구현할 때 기존 JDK에서 제공하는 예외 클래스 중 가장 유사한 클래스를 상속받는 것이 좋음.
유사한 예외 클래스를 잘 모르겠다면 가장 상위 클래스인 Exception 클래스에서 상속받으면 됨.
package test12;
//사용자 정의 예외
//나이가 음수이거나 120보다 큰 경우에 예외 처리 만들기
class AgeException extends Exception {
// 기본생성자
public AgeException() {
super();
}
// 일반생성자
// 상속을 받게 되면 부모(상위) 클래스의 생성자를 호출해서 멤버 변수값을 초기화 해야함
public AgeException(String message){
// Exception 클래스의 생성자를 호출해서 멤버 변수에 데이터값을 초기화
super(message); // 부모(상위)생성자 호출 해서 매개변수로 입력받은 문자열을 멤버 변수에 저장
}
}
public class ExceptionTest6 {
//throws : 메소드를 호출하면서 메소드 쪽으로 예외처리를 떠넘김
//throw : 강제로 예외 발생 시킴
public static void ticketing(int age) throws AgeException {
if (age < 0 || age > 120) {
AgeException e = new AgeException("나이 입력이 잘못되었습니다.");
throw e;
} else {
System.out.println("나이가 " + age + " 이므로 ticketing 되었습니다.");
}
}
public static void main(String[] args) {
int age = 10;
try {
ticketing(age);
} catch (AgeException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("사용자 정의 AgeException이 수정됨");
}
// try {
// ticketing(age);
// } catch (AgeException e) {
// e.printStackTrace();
// Exception 발생 경로를 추적하도록 표시해주는 메소드
// }
}
}
위의 예시와 p507과 유사
728x90
'KDT > Java' 카테고리의 다른 글
240131 Java - 자바 입출력 (0) | 2024.01.31 |
---|---|
240129 Java - 날짜와 시간을 다루는 클래스 (0) | 2024.01.29 |
240124 Java - 예외 1 (0) | 2024.01.24 |
240115 Java (0) | 2024.01.15 |
240111 Java (0) | 2024.01.11 |