예외처리 (Try Catch)
package chap_11;
public class _01_TryCatch {
public static void main(String[] args) {
// 예외 처리
// 오류 : 컴파일 오류, 런타임 오류 (에러 error, 예외 exception)
try {
// System.out.println(3 / 0);
// int[] arr = new int[3];
// arr[5] = 100;
Object obj = "test";
System.out.println((int) obj);
} catch (Exception e) {
System.out.println("이런 문제가 발생했어요 => " + e.getMessage());
e.printStackTrace();
}
System.out.println("프로그램 정상 종료");
}
}
Catch 구문
package chap_11;
public class _02_Catch {
public static void main(String[] args) {
try {
// System.out.println(3 / 0);
int[] arr = new int[3];
arr[5] = 100;
// Object obj = "test";
// System.out.println((int) obj);
// String s = null;
// System.out.println(s.toLowerCase());
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("뭔가 실수 하셨네요.");
//} catch (ArrayIndexOutOfBoundsException e) {
// System.out.println("뭔가 실수 하셨네요.");
} catch (ClassCastException e) {
System.out.println("잘못된 형 변환입니다.");
} catch (Exception e) {
System.out.println("그 외의 모든 에러는 여기서 처리가 돼요.");
e.printStackTrace();
}
System.out.println("프로그램 정상 종료");
}
}
Throw 구문
package chap_11;
public class _03_Throw {
public static void main(String[] args) {
int age = 17; // 만 17세
try {
if (age < 19) {
// System.out.println("만 19세 미만에게는 판매하지 않습니다.");
throw new Exception("만 19세 미만에게는 판매하지 않습니다.");
} else {
System.out.println("주문하신 상품 여기 있습니다.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
'인강 보습 (인프런,유데미,패스트캠퍼스) > 나도코딩의 자바 기본편' 카테고리의 다른 글
쓰레드 - (1) Thread, Runnable, Join (0) | 2023.01.19 |
---|---|
예외처리 (2) - Finally, Try with Resources, 사용자 정의 예외, 예외처리미루기 (0) | 2023.01.19 |
익명 클래스, 람다와 스트림 - (2) 함수형 인터페이스, 스트림 (0) | 2023.01.19 |
익명 클래스, 람다와 스트림 - (1) 익명클래스, 람다 (0) | 2023.01.19 |
제네릭스 (3) - HashSet, HashMap, Iterator (0) | 2023.01.18 |