int a = 99.9; => int a = (int)99.9; // 코드 수정 가능!
int[] arr = new int[3]; // 길이 3 : 인덱스가 0, 1, 2 까지
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
// java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
// 배열 범위 초과 예외
if(3 >= arr.length) { // 배열 인덱스 범위 초과한 값이 들어왔다면
System.out.println("배열 범위를 초과했습니다");
} else {
arr[3] = 40;
System.out.println("배열 범위 안정적..");
}
}
}


ArithmeticException
0으로 나누는 경우 발생
if문으로 나누는 수가 0인지 검사
NullPointerException
Null인 참조 변수로 객체 멤버 참조 시도 시 발생
객체 사용 전에 참조 변수가 null인지 확인
NegativeArraySizeException
배열 크기를 음수로 지정한 경우 발생
배열 크기를 0보다 크게 지정해야 함
ArrayIndexOutOfBoundsException
배열의 index범위를 넘어서 참조하는 경우
배열명.length를 사용하여 배열의 범위 확인
ClassCastException
Cast연산자 사용 시 타입 오류
instanceof 연산자로 객체타입 확인 후 cast연산
InputMismatchException
Scanner를 사용하여 데이터 입력 시
입력 받는 자료형이 불일치할 경우 발생
ex)
try{
// 예외가 발생할 가능성이 있는 코드
} catch(IndexArrayOutOf..Exception e) {
e.printStackTrace();
처리하고 싶은 내용..
} finally {
// 예외 발생 여부와 관계없이 마지막에 반드시 수행해야 하는 코드 작성
}
try : Exception 발생(throw)할 가능성이 있는 코드를 안에 기술
catch : try 구문에서 Exception 발생 시(throw) 해당하는 Exception에 대한 처리 기술
여러 개의 Exception 처리가 가능하나 Exception간의 상속 관계 고려해야 함
finally : Exception 발생 여부와 관계없이 꼭 처리해야 하는 로직 기술
중간에 return문을 만나도 finally구문은 실행되지만
System.exit();를 만나면 무조건 프로그램 종료
주로 java.io나 java.sql 패키지의 메소드 처리 시 이용
* sc.close();로 통로를 닫아 메모리 누수를 방지한다
public void method() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("입력 : ");
String str = br.readLine();
System.out.println("입력된 문자열 : " + str);
} catch (IOException e) {
e.printStackTrace();
}
}
public void method() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("입력 : ");
String str = br.readLine();
System.out.println("입력된 문자열 : " + str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { // finally 안에 try ~ catch가 또 중복
System.out.println("BufferedReader 반환");
br.close(); // 스캐너 통로 닫기 : 메모리 누수 방지
} catch (IOException e) {
e.printStackTrace();
}
}
}
throw : 예외 강제 발생 구문
throws : 호출한 메서드에게 예외를 위임(던짐)

public void ex4() {
try {
methodA();
} catch(IOException e) {
// IOException의 부모인 Exception도 가능
System.out.println("methodC에서부터 발생한 예외를 ex4에서 잡아서 처리함");
}
}
public void methodA() throws IOException {
methodB();
}
public void methodB() throws IOException {
methodC();
}
public void methodC() throws IOException {
// throws : 호출한 메서드에게 예외를 던짐
// -> 호출한 메서드에게 예외처리를 하라고 위임하는 행위
// throw : 예외 강제 발생 구문
throw new IOException(); // Checked Exception이라
// 반드시 처리해야해서 빨간줄뜸
}


public void ex5() throws UserException {
// 사용자 정의 예외 클래스인 UserException 사용하여 강제 예외 발생시키기
throw new UserException("사용자정의 예외 발생");
}
↓↓↓↓던져서↓↓↓↓
// 사용자 정의 예외 클래스
public class UserException extends Exception{
public UserException() {}
public UserException(String message) {
super(message);
}
↓↓↓↓ ↓↓↓↓
public class ExceptionRun {
public static void main(String[] args) {
try {
new ExceptionService().ex5();
} catch (UserException e) {
System.out.println(e.getMessage());
}
}
}