<try-catch>문의 기본 구조
try {
...
} catch (예외1) {
...
} catch (예외2) {
....
} finally {
System.out.println("이건 반드시 실행되어야 합니다.");
}
<throw 사용 예시>
if () {
throw new IllegalArgumentException("부적절한 이름입니다.");
// throw new IllegalArgumentException 구문을 풀어 쓴 경우
// IllegalArgumentException e = new IllegalArgumentException("부적절한 이름입니다.");
// throw e;
}
<throws 사용 예시>
// 메소드 호출
public static void main(String[] args) {
SayHello sayHello = new SayHello();
try {
sayHello.sayHello();
} catch (Exception1 e) {
System.out.println("예외가 발생하였습니다");
}
}
// 메소드 선언
public static void sayHello() throws Exception1, Exception2..ExceptionN {
//....
}
/*
* 이것은 커스텀 CheckedException 입니다.
* 자바의 기본 예외로 표현할 수 없는 예외를 제공하기 위해 만들어졌습니다.
* */
public class CustomCheckedExceptionEx extends Exception {
public CustomCheckedExceptionEx() {
}
public CustomCheckedExceptionEx(String message) {
super(message);
}
public CustomCheckedExceptionEx(String message, Throwable cause) {
super(message, cause);
}
public CustomCheckedExceptionEx(Throwable cause) {
super(cause);
}
public CustomCheckedExceptionEx(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
class CustomCheckedExceptionTest {
public static void main(String[] args) throws CustomCheckedExceptionEx {
try {
// doSomething
} catch (Exception e) {
throw new CustomCheckedExceptionEx("커스텀 체크드 예외 발생!!", e);
}
}
}
public class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException() {
}
public CustomUncheckedException(String message) {
super(message);
}
public CustomUncheckedException(String message, Throwable cause) {
super(message, cause);
}
public CustomUncheckedException(Throwable cause) {
super(cause);
}
public CustomUncheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
class CustomUncheckedExceptionTest {
public static void main(String[] args) {
try {
// doSomething
} catch (RuntimeException e) {
throw new CustomUncheckedException("커스텀 언체크드 예외 발생!!", e);
}
}
}
[참고]
https://parkadd.tistory.com/69
https://zannew.tistory.com/23
https://velog.io/@zayson/%EB%B0%B1%EA%B8%B0%EC%84%A0%EB%8B%98%EA%B3%BC-%ED%95%A8%EA%BB%98%ED%95%98%EB%8A%94-Live-Study-9%EC%A3%BC%EC%B0%A8-%EC%98%88%EC%99%B8-%EC%B2%98%EB%A6%AC
https://youn12.tistory.com/32