JAVA Programming

[79] 예외처리미루기 , 사용자정의예외 , throws 미루기,throw 예외발생

꾸준히개발하자 2020. 7. 21. 08:55

예외 처리 미루기

Throws (미루다) 를 사용하여 예외처리 미루기

Try{} 블록으로 예외를 처리하지 않고 , 메소드 선언부에 throws 를 추가 한다.

예외가 발생한 메소드에서 예외처리를 하지 않고 이 메소드를 호출한 곳에서 예외 처리를 한다는 의미이다.

Main() 에서 throws 를 사용하면 가상 머신에서 처리된다.

이 메소드를 호출하는곳에서 처리

 

package exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

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("b.txt", "java.lang.String");
		} catch (FileNotFoundException e) {
			System.out.println(e);
		} catch (ClassNotFoundException e) {
			System.out.println(e);
		} catch (Exception e) { // 최상위 이셉션  위에 걸어두면 안된다.
		System.out.println("end");
		}
	}
}

하단에  최상위 클래스 이셉션 Exception e 처리한다  상단에 놓으면 오류가 발생 

 

 

 

 extedns 로 Exception 를 상속받는다. 

 

Public IDFormatException (String message)  생성자의 매개변수로 예외 상황 메시지를 받는다.

super(message); 

 

package exception;

// 이셉션을 만들때는 이셉션을 상속받으면 된다. 
public class IDFormatException extends Exception {
	
	public IDFormatException(String message) {
		
		super(message); // 이셉션에 메시지내용이 보인다. 
	}
}

 

 

 

 

 

package exception;

// 이셉션을 만들때는 이셉션을 상속받으면 된다. 
public class IDFormatException extends Exception {
	
	public IDFormatException(String message) {
		
		super(message); // 이셉션에 메시지내용이 보인다. 
	}
}
package exception;

public class IDFormatTest {
	
	private String userID;
	
	public String getUserID() {
		return userID;
	}
	
	// set할때 이셉션처리  아이디 넘어온게 null 이거나 
	// throws 미루는거고 throw는 이셉션발생
	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);
		} 
	}
}