package exception;
public class Main01 {
public static void main(String[] args) {
// 문자열의 숫자 변환에 아무런 문제가 없다
String year1 = "1980";
int age1 = 2024 - Integer.parseInt(year1) +1;
System.out.println(age1);
// 숫자로 변환할 수 없으므로, 에러 발생
String year2 = "뭘까요?";
int age2 = 2024 - Integer.parseInt(year2) + 1;
System.out.println(age2);
System.out.println("--- 프로그램 종료 ---");
}
}
package exception;
public class main02 {
public static void main(String[] args) {
int[] arr = new int[3];
for(int i=0; i<5; i++) {
if(i < arr.length
) {
arr[i] = i; // i가 3일 때 에러 발생
System.out.println(i);
}
}
}
}
컴파일 에러
-> 소스 코드의 구문 오류로 인하여 캄파일이 불가능한 상태
-> 이클립스에서 빨간색으로 표시되는 경우에 행당
-> 프로그램을 실행하기 전에 발견되므로 상대적으로 고치기 쉬움
런타임 에러
-> 구문상의 에러는 엉ㅄ지만, 프로그램이 실행되는 과젱에서 다양한 경우의 수에 대응하지 못하여 발생하는 예외 상황
-> 런타임 에러가 발생하면 프로그램은 강제로 종료
-> 우리가 프로그램의 에러라고 부른느 현상은 대부분 런타임 에러에 해당
package exception;
public class Main03 {
public static void main(String[] args) {
try {
String year2 = "뭘까요?";
int age2 = 2024 - Integer.parseInt(year2) + 1;
System.out.println(age2);
} catch (NumberFormatException e) {
e.printStackTrace();
//System.out.println("에러가 발생했습니다.");
//System.out.println("원인 : "+e.getMessage());
}
System.out.println("--- 프로그램 종료 ---");
}
}
package exception;
public class main04 {
// ArrayIndexOutOfBoundsException
//try ~ catch,
public static void main(String[] args) {
try {
int[] arr = new int[3];
for(int i=0; i<5; i++) {
arr[i] = i; // i가 3일 때 에러 발생
System.out.println(i);
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println("오류 발생");
System.out.println("원인 : "+e.getMessage());
}
System.out.println("--- 프로그램 종료 ---");
}
}
package exception;
public class Main05 {
public static void main(String[] args) {
// 사용자가 입력값을 가정
String[] src = {"가", "2", "aaa", "ccc"};
// src의 내용들을 숫자로 변환해서 저장할 배열
int[] arr = new int[3];
// for문 try 구문 처리
try {
for(int i=0; i<src.length; i++) {
arr[i] = Integer.parseInt(src[i]);
System.out.println(arr[i]);
}
}
// catch : NumberFormatException
// catch : ArratIndexoutOfBoundsException
// catch : Excetpion
catch (NumberFormatException e) {
System.out.println("입력값에 오류가 있습니다");
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("데이터가 너무 많습니다.");
e.printStackTrace();
}
catch (Exception e) {
// 이 블록은 모든 종류의 예외에 대처할 수 있음
// 예외 종류를 의미하는 모든 클래스는
// java.lang.Exception 클래스를 상속 받음
System.out.println("알 수 없는 예외가 발생했습니다.");
e.printStackTrace();
}
// finally : "데이터 변환 종료"
finally {
System.out.println("--- 데이터 변환 종료 ---");
}
System.out.println("--- 프로그램 종료 ---");
}
}