예외처리 미루기
throws를 사용하여 예외 처리를 이룬다.
try블록을 구현하지 않는 대신 메서드 선언부에 throws를 추가하면 해당 헤서드를 호출한 곳에서 예외를 처리한다.
main에서 throws를 사용하면 가상머신에서 처리된다.
다중 예외 처리
가장 최상위 클래스인 Exception 클래스는 가장 마지막 블록에 위치해야 한다.
그렇지 않으면 Exception 아래에 위치한 다른 클래스들이 전부 업캐스팅되어 실행되지 않음!
/**
* @topic throws 구현
* @description throws를 통해 예외처리를 지연시킨다. 해당 함수가 아닌 다른 함수에서 예외처리를 실행함
*/
public class ThrowsException {
public Class loadClass(String fileName, String className) throws FileNotFoundException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
Class c = Class.forName(className);
return c;
}
public static void main(String[] args) {
ThrowsException test = new ThrowsException();
try {
test.loadClass("a.txt", "java.lang.String");
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (Exception e) {
// Exception은 항상 마지막에 위치
}
}
}
사용자 정의 예외
기존 JDK의 Exception 클래스를 상속받아서 예외 클래스를 만든다.
throw키워드로 예외를 발생시킨다.
public class IDFormatException extends Exception {
public IDFormatException(String msg) {
super(msg);
}
}
public class IDFormatTest {
private String userID;
public String getUserID() {
return userID;
}
public void setUserID(String userID) throws IDFormatException {
if (userID == null) {
throw new IDFormatException("아이디는 null일 수 없습니다.");
} else if (userID.length() < 8 || userID.length() > 20) {
throw new IDFormatException("아이디는 8자 이상 20자 이하로 쓰세요");
}
this.userID = userID;
}
public static void main(String[] args) {
IDFormatTest idTest = new IDFormatTest();
String myID = null;// 테스트를 위한 아이디 예시
try {
idTest.setUserID(myID);
} catch (IDFormatException e) {
System.out.println(e);
}
myID = "123456"; // 테스트를 위한 아이디 예시
try {
idTest.setUserID(myID);
} catch (IDFormatException e) {
System.out.println(e);
}
}
}
'프로그래밍 언어 > java' 카테고리의 다른 글
[java] 예외 처리 (0) | 2021.04.05 |
---|---|
[java] Class 클래스, 자바 리플렉션 (0) | 2021.03.18 |
[java] String, Wrapper 클래스 (0) | 2021.03.18 |
[java] Object 클래스 (0) | 2021.03.18 |
[java] 인터페이스 다중 상속 (0) | 2021.03.12 |
댓글