실행하는 단계에서 발생한 오류(예외)를 프로그램적으로 처리한다는 의미
관련 키워드
try ~ catch ~ finally 블럭
throws 키워드
위 두 개 중
형식)
try {
예외가 발생할 가능성이 있는 코드;
}catch(예외클래스 참조변수) {
예외가 발생한 경우 실행되는 코드;
참조변수 : 예외와 관련된 정보를 넘겨받는 변수
}finally {
// 생략이 가능함
예외와 상관없이 실행되어야 하는 코드;
}
<예시1>
=============================코드=============================
public static void main(String[] args) {
System.out.println("프로그램 시작");
int num1 = 10, num2 = 0;
int result = 0;
try {
result = num1 / num2; // 예외가 발생할 가능성이 있는 코드
} catch(Exception e) { // e는 변수명처럼 아무거나 선언해도 됨
System.out.println("0으로 나눈 예외 발생");
System.out.println("예외 정보 >>> " + e);
}
System.out.println("result >>> " + result);
System.out.println("프로그램 종료");

<예시2>
=============================코드=============================
public static void main(String[] args) {
System.out.println("프로그램 시작");
String str1 = "korea";
String str2 = null; // 값이 없는 상태
try {
System.out.println("str1 문자열의 길이 >>> " + str1.length());
System.out.println("str2 문자열의 길이 >>> " + str2.length());
}catch(Exception s) {
System.out.println("null 값을 갖는 오류 발생");
System.out.println("예외정보 >>> " + s);
}
System.out.println("프로그램 종료");
}

<예시3>
=============================코드=============================
public static void main(String[] args) {
System.out.println("프로그램 시작");
Scanner sc = new Scanner(System.in);
try {
int su = sc.nextInt();
System.out.println("입력 받은 정수 >>> " + su);
}catch(Exception s) {
System.out.println("정수만 입력하세요");
System.out.println("예외 정보 >>> " + s);
}finally {
// 입출력과 관련된 데이터를 처리하는 코드
sc.close();
}
System.out.println("프로그램 종료");
}


**어려운 점
-try에 작성할 코드와 catch에 작성할 코드를 명확히 아는 것이 필요..! 잘 구분 할 수 있도록 여러 예외 상황 처리를 연습하자!!