카테고리 없음
#7 <4주차> Exception
kmsoon
2024. 5. 8. 16:58
Throw와 Throws
throw는 개발자가 의도적으로 예외를 발생시키는 것이다
public class Test {
public static void main(String[] args) {
int a = 2;
int b = 0;
divide(a,b);
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("0으로 나눌 수 없습니다.");
}
return a / b;
}
}
throws는 메서드 내에서 예외처리를 하지 않고 해당 메서드를 사용한 곳에서 예외 처리를 하도록
예외를 던지는 것이다 (예외를 전가한다)
public class Test {
public static void main(String[] args) {
int a = 2;
int b = 0;
try {
divide(a,b);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("0으로 나눌 수 없습니다.");
}
return a / b;
}
}
Finally
예외 발생 여부와 상관없이 반드시 실행되는 구문
public class trycatchTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int [] num = new int[3];
System.out.println("num 배열의 최대 길이는 3입니다.");
num[4] = 0;
System.out.println("num[4] 에 값을 입력했습니다.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열 길이가 맞지 않습니다.");
} finally {
System.out.println("배열을 다시 선언합니다");
int [] num = new int[5];
num[4] = 0;
System.out.println(num[4]);
}
System.out.println("프로그램을 종료합니다");
}
}
Chained Excepton (연결된 예외)
예외 A가 예외 B를 발생시켰다면, 예외 A는 B의 원인 예외입니다.
원인 예외를 새로운 예외에 등록한 후 다시 새로운 예외를 발생 시키는데 이를 예외 연결이라고 한다
initCause()
지정한 예외를 원인 예외로 등록하는 메소드
getCause()
원인 예외를 반환하는 메소드
// 연결된 예외
public class main {
public static void main(String[] args) {
try {
// 예외 생성
NumberFormatException ex = new NumberFormatException("가짜 예외이유");
// 원인 예외 설정(지정한 예외를 원인 예외로 등록)
ex.initCause(new NullPointerException("진짜 예외이유"));
// 예외를 직접 던집니다.
throw ex;
} catch (NumberFormatException ex) {
// 예외 로그 출력
ex.printStackTrace();
// 예외 원인 조회 후 출력
ex.getCause().printStackTrace();
}
// checked exception 을 감싸서 unchecked exception 안에 넣습니다.
throw new RuntimeException(new Exception("이것이 진짜 예외 이유 입니다."));
}
}
// 출력
Caused by: java.lang.NullPointerException: 진짜 예외이유
*타입변수는 인스턴스 변수로 간주됨*