2020년 11월 12일
업데이트:
예외 처리
finall
Exception 발생 여부와 관계없이 꼭 처리해야 하는 로직 기술이다. 중간에 return문을 만나도 finally구문은 실행되지만 System.exit();
를 만나면 무조건 프로그램이 종료된다. 주로 java.io.나 java.sql 패키지의 메소드 처리 시 이용된다.
public void example5() throws Exception {
// 정수를 두 개 입력받아 나누어 몫을 출력하는 프로그램
// 발생할 수 있는 예외 : 0으로 나눴을 때, 정수가 아닌 값을 입력했을 때
Scanner sc = new Scanner(System.in);
try {
System.out.print("입력 1 : ");
int num1 = sc.nextInt();
System.out.print("입력 2 : ");
int num2 = sc.nextInt();
System.out.println("결과 : " + num1 / num2);
throw new Exception();
}catch(InputMismatchException e){
System.out.println("정수만 입력해주세요.");
e.printStackTrace();
}catch(ArithmeticException e){
System.out.println("0으로 나눌 수 없습니다.");
System.out.println(e.getMessage());
e.printStackTrace();
}catch(Exception e) {
e.printStrackTrace();
}
finally {
System.out.println("프로그램 종료");
}
}
throws
메소드 선언 시 throws
를 추가하여 호출한 상위 메소드에게 처리를 위임한다. 계속 위임을 하게 되면 main()메소드까지 위임하게 되고 main()메소드에서도 처리되지 않는 경우엔 프로그램이 비정상 종료된다.
public void example6() {
System.out.println("6 호출됨.");
try{
example6_1();
}catch(ArithmeticException e){
System.out.println("0으로 나눌 수 없습니다.");
}catch(NullPointerException e){
System.out.println("NullPointerException이 발생했습니다.");
}
}
public void example6_1() throws ArithmeticException, NullPointerException {
System.out.println("6_1 호출됨");
example6_2();
}
public void example6_2() throws ArithmeticException, NullPointerException{
System.out.println("6_2 호출됨.");
example6_3();
}
public void example6_3() throws ArithmeticException{
System.out.println("6_3 호출됨.");
// 예외를 강제로 발생시켜 던지기
//throw new NullPointerException();
// NullPointerException은 RuntimeException의 후손으로
// UncheckdException 분류에 포함되어 별도의 예외처리가 없어도 된다.
throw new InputZeroException();
//InputZeroException 클래스처럼 RuntimeException이 아닌 다른 예외 클래스를 상속한 클래스들은
// 모두 CheckedException 분류에 포함되어
// 반드시 예외처리가 필요함.
}
사용자 정의 예외
Exception 클래스를 상속받아 예외 클래스를 작성하는 것으로 자바 API에서 제공하는 예외 클래스만으로는 처리할 수 없는 예외가 있을 경우 사용자의 필요에 따라 생성하는 예외 클래스이다.
public void example7() {
try {
System.out.println("프로그램 실행");
sumMethod();
System.out.println("프로그램 정상 종료");
}catch(InputZeroException e){
System.out.println(e.getMessage());
System.out.println("비정상 종료");
e.printStackTrace();
}
}
public void sumMethod() throws InputZeroException {
Scanner sc = new Scanner(System.in);
int sum = 0;
for(int i = 0; i < 3; i++){
System.out.print("입력" + (i + 1) + " : ");
int num = sc.nextInt();
if(num == 0) {
throw new InputZeroException("0 좀 입력하지마");
}
sum += num;
}
System.out.print("합계 : " + sum);
}
// InputZeroException.java
public class InputZeroException extends RuntimeException{
// 예외로 만드려고하는 클래스에 Exception 관련 클래스 상속
public InputZeroException() {
System.out.println("0이 입력되었습니다.");
}
//오버로딩
public InputZeroException(String msg) {
super(msg);
}
공유하기
Twitter Google+ LinkedIn
댓글남기기