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;
}
//Exception은 최상위 exception이므로 맨처음에 선언하면 안된다. 항상 업캐스팅 되어서 먼저 실행됨
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){
System.out.println(e);
}
System.out.println("end");
}
}
IDformatException.java
package exception;
public class IDformatException extends Exception{
public IDformatException(String message) {
super(message);
}
}
IDFormatTest.java
package exception;
public class IDFormatTest {
public 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) {
e.printStackTrace();
}
//exception.IDformatException: 아이디는 null 일 수 없습니다.
myId="123456";
try {
idTest.setUserID(myId);
} catch (IDformatException e) {
e.printStackTrace();
}
//exception.IDformatException: 아이디는 8자 이상 20자 이하로 쓰세요.
}
}