[JAVA][패스트캠퍼스]다양한 예외처리

12828 단어 JavafastcampusJava

예외처리 미루기

  • throws를 사용하여 예외처리 미루기
  • try{} 블록으로 예외를 처리하지 않고, 메서드 선언부에 throws를 추가
  • 예외가 발생한 메서드에서 예외 처리를 하지 않고 이 메서드를 호출한 곳에서 예외 처리를 한다는 의미
  • main()에서 throws를 사용하면 가상머신에서 처리됨

다중예외 처리하기

  • 하나의 try{}블록에서 여러 예외가 발생하는 경우 catch{}블록 한곳에서 처리하거나 여러 catch{}블록으로 나누어 처리할 수 있음
  • 가장 최상위 클래스인 Exception클래스는 가장 마지막 블록에 위치 해야함
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");
	}
}

사용자 정의 예외

  • JDK에서 제공되는 예외 클래스 외에 사용자가 필요에 의해 예외 클래스를 정의하여 사용
  • 기존 JDK클래스에서 상속받아 예외 클래스 만듬
  • throw 키워드로 예외를 발생시킴

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자 이하로 쓰세요.
	}
}

좋은 웹페이지 즐겨찾기