728x90
목차
1. 예외
■ 예외란?
- 예외는 발생할 수 있는 에러 사항을 말함
- 일반 예외와 실행 예외가 있음
- 해당하는 예외가 바로 runtime exception을 상속받으면 실행 예외이고 exception을 상속받으면 일반 예외임
- 일반 예외는 개발자가 반드시 예외 처리를 해야함
- 실행 예외는 개발자가 예외 처리를 직접 하지 않아도 되며, 명시적인 에외 처리가 강제되는 것이 아님
■ 실행 예외 종류
- NullPonterException
- ArrayIndexOutOfBoundsException
- NumberFormatException
- ClassCastException
2. 예외 처리
■ 예외 처리
- 예외 처리는 try ~ catch문으로 해결함
- try문에는 예외가 일어날 것 같은 코드를 넣음
- catch문은 예외 발생 시 예외를 잡아줌
- 다중 catch문 작성 시 상위 예외 클래스가 하위 에외 클래스보다 밑에 작성해야 함
- finally문은 try ~ catch ~ finally로 구성하며 try, catch문이 실행되어도 무조건 실행됨
- finally는 catch에 하위 예외를 넣어둘 경우 실행이 안되도 반드시 실행하도록 함
■ 예외 떠넘기기
- 예외 떠넘기기는 메소드를 호출한 곳으로 예외 처리를 넘기는 것
- 예외 떠넘기기 시 사용하는 키워드는 throws임
- 일반 예외로 반드시 체크해줘야하기 때문에 throws Exception으로 넘겨주고 호출한 곳에서 try ~ catch문으로 체크함
3. 예시
■ ArrayException
package j21_예외;
import java.nio.file.Files;
import java.sql.DriverManager;
public class ArrayException {
public static void main(String[] args) {
Integer[] nums = { 1, 2, 3, 4, 5 };
try {
// 강제로 예외를 발생시킴
throw new NullPointerException();
// IndexOutOfBoundsException예시
// for (int i = 0; i < 6; i++) {
// System.out.println(nums[i]);
// }
// 다른 예외 처리 불가
} catch (IndexOutOfBoundsException e) {
System.out.println("예외 처리함");
// 다른 예외 처리 불가
} catch (NullPointerException e) {
System.out.println("빈값 처리함");
// 위에서 부터 타고 내려와 Exception이 제일 마지막에 위치
} catch (Exception e) {
System.out.println("예상 못한 예외 처리함");
}
System.out.println("프로그램 정상 종료");
}
}
■ ThrowsException
package j21_예외;
import java.util.Arrays;
import java.util.List;
public class ThrowsException {
// 일반 예외로 반드시 체크해줘야해서 throws Exception로 넘겨주고 try ~ catch문으로 체크함
public static void printList(List<String> list, int size) throws Exception {
for (int i = 0; i < size; i++) {
System.out.println("[" + i + "]" + list.get(i));
}
System.out.println();
}
public static void main(String[] args) {
String[] names = { "김수현", "이종현", "박성진", "김동민" };
try {
printList(Arrays.asList(names), 5);
} catch (Exception e) {
// 지금 발생한 예외가 어떤 예외인지 알려줌
// e.printStackTrace();
// Exception 대신 하위 예외를 잡을 경우에 사용
// 예상치 못한 에러가 발생할 경우 실행
// 무조건 실행하기 때문에 저장하는 작업을 넣어줌
} finally {
System.out.println("무조건 실행");
}
System.out.println("프로그램 정상 종료");
}
}
■ CustomErrorException
package j21_예외;
// 내가 예외 생성 시 RuntimeException을 상속받음
public class CustomErrorException extends RuntimeException {
public CustomErrorException() {
System.out.println("내가 만든 예외 생성");
}
public CustomErrorException(String message) {
// Throwable가 최상위이므로 최상위로 전달하여 메세지 출력
super(message);
}
}
■ CustomExceptionMain
package j21_예외;
public class CustomExceptionMain {
public static void main(String[] args) {
// 예외에는 메세지를 줄수 있음
// throw new IndexOutOfBoundsException("인덱스를 초과함");
try {
throw new CustomErrorException("뭔가 문제가 있음");
} catch (CustomErrorException e) {
String message = e.getMessage();
System.out.println(message);
}
System.out.println("프로그램 종료");
}
}