[JAVA] Checked exception vs Unchecked exception

정만·2023년 2월 19일

JAVA

목록 보기
1/4

자바 예외 종류

1. Checked Exception :

명시적인 예외 처리를 강제한다.
반드시 try~catch로 예외를 잡거나, throw로 호출한 메소드에게 예외를 던져야 한다.

2. Unchecked Exception :

명시적인 예외 처리를 강제하지 않는다.
RuntimeException을 상속하는 예외 클래스이다.

그렇다면 예외란 무엇일까?

예외(Exception)란 입력 값에 대한 처리가 불가능하거나, 프로그램 실행 중에 참조된 값이 잘못된 경우 등 정상적인 프로그램의 흐름을 어긋나는 것을 말한다.
자바에서 예외는 개발자가 직접 처리할 수 있기 때문에 예외 상황을 미리 예측하여 핸들링할 수 있다.

Checked Exception 예시

package Exception.example;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
public class CheckedException {
 
public static void main(String args[]) {
  FileInputStream fis = null;
 
  try {
   fis = new FileInputStream("sample.txt");
 
   int c;
                        while ((c = fis.read()) != -1) {
    System.out.print((char) c);
   }
 
   fis.close();
 
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
}
 
}

try~catch문 이용하여 해결

package Exception.example;
 
import java.io.FileInputStream;
import java.io.IOException;
 
public class CheckedException {
 
public static void main(String args[]) throws IOException {
  FileInputStream fis = null;
   fis = new FileInputStream("sample.txt");
   int k;
   while ((k = fis.read()) != -1) {
    System.out.print((char) k);
   }
 
   fis.close();
}
}

Unchecked Exception 예시

package Exception.example;
 
public class ArrayIndexOutOfBoundExceptionExample {
public static void main(String args[]){
 
  String strArray[]={"Arpit","John","Martin"};
  System.out.println(strArray[4]);
	}
}

결과

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at org.arpit.java2blog.ArrayIndexOutOfBoundExceptionExample.main(ArrayIndexOutOfBoundExceptionExample.java:7)
 
profile
멋있는 어른이 되고싶은 정만이의 벨로그

0개의 댓글