public class MyCheckedException extends Exception{
public MyCheckedException(String message) {
super(message);
}
//예외 클래스를 만들려면 예외를 상속 받으면 된다.
//`Exception` 을 상속받은 예외는 체크 예외가 된다.
}
public class Client {
public void call() throws MyCheckedException{
throw new MyCheckedException("ex");
}
}
throw 예외` 라고하면새로운예외를발생시킬수있다. 예외도객체이기때문에객체를먼저
`new`로생성하고예외를발생시켜야한다.
`throws 예외` 는발생시킨예외를메서드밖으로던질때사용하는키워드이다.
`throw` , `throws` 의차이에주의하자
public class Service {
Client client = new Client();
public void callCatch() {
// 예외를 잡아서
// 처리하는코드
try {
client.call();
} catch (MyCheckedException e) {
System.out.println("예외 처리 : "+e.getMessage());
}
System.out.println("정상 흐름");
}
//예외를 잡지않고 던지는 코드
public void callThrow() throws MyCheckedException{
client.call();
}
}
예외를 잡아서 처리 -main
public class CheckedMain {
public static void main(String[] args) {
Service service = new Service();
System.out.println("예외를 잡아서 처리");
service.callCatch();
System.out.println("정상종료");
}
}
public class MyUncheckedException extends RuntimeException{
public MyUncheckedException (String message) {
super(message);
}
}
public class Client {
public void call() {
throw new MyUncheckedException("ex");
}
}
public class Service {
Client client = new Client();
public void callCatch() {
try {
client.call();
} catch (MyUncheckedException e) {
System.out.println(e.getMessage());
}
System.out.print("정상 로직");
}
// 예외를 잡지 않아도된다
// 자연스럽게 상위로 넘어감.
// 체크예외와 다르게 throws선언 안해도 됨
public void callThrow() {
client.call();
}
}
public class UncheckedMain {
public static void main(String[] args) {
Service service = new Service();
service.callCatch();
System.out.println("정상종료");
}
}
ex
정상 로직
정상종료
체크예외와 같은 출력이 나오는것을 확인
publicclassUncheckedThrowMain{
publicstaticvoidmain(String[]args){
Serviceservice=newService();
service.callThrow();
System.out.println("정상종료");
}}
Exception in thread "main" exception.basic.unchecked.MyUncheckedException: ex
at lang/exception.basic.unchecked.Client.call(Client.java:5)
at lang/exception.basic.unchecked.Service.callThrow(Service.java:19)
at lang/exception.basic.unchecked.UncheckedThrowMain.main(UncheckedThrowMain.java:6)