Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

Super Coding Addict

Ch13. 예외 처리 본문

JAVA 문법

Ch13. 예외 처리

밍응애 2021. 2. 9. 23:52

* 예외 처리 미루기

- try{}블록으로 예외를 처리하거나, throws를 해서 예외처리를 미룰 수 있다

- 예외처리를 미루면(throws), 메서드를 호출한 곳에서 예외처리를 하게 된다

- main()에서 throws를 하면 가상머신에서 처리되므로 에러발생!

 

* 다중 예외 처리

- 하나의 try{}블록 안에서 여러 블록이 발생하면 catch{}블록 한 곳에서 모두 처리(멀티)하거나,

   여러 catch{}블록으로 나눠 처리 가능

- 가장 최상위 Exception 클래스인 Exception클래스는 가장 마지막 블록에 위치해야 함!

 

* 사용자 정의 예외

- JDK 제공 예외 클래스외에, 시스템상 사용자가 필요에 의해서 예외 클래스 정의하여 사용할 수 있음

- 기존 JDK 클래스 상속해 만듦

 

* 예제 1

# ThrowsException 클래스 

package ch13.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) {	//디폴트 Excpetion, 최상위이므로 항상 제일 마지막에!
			System.out.println(e);
		}
		System.out.println("end");

	}

}

--> main에서는 throws를 하면 안되고, try-catch로 처리해줘야함

--> 최상위 Exception은 제일 마지막 catch{}에

 

* 예제 2 - 커스텀 Exception

# IDFormatException 클래스

package ch13.exception;

public class IDFormatException extends Exception{

	public IDFormatException(String message) {
		super(message);
	}
}

--> 커스텀 Exception은 JDK에서 제공하는 Exception을 상속, 구체적인 Exception종류여도 좋지만 모르겠으면 최상위 Exception을 상속

 

# IDFormatTest 클래스 (메인)

package ch13.exception;

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 일 수 없습니다.");
			//Exception 발생시키기
		}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);
		}
	}

}
결과 :
ch13.exception.IDFormatException: 아이디는 null 일 수 없습니다.
ch13.exception.IDFormatException: 아이디는 8자 이상 20자 이하로 쓰세요.

--> userID setter에서 예외 상황들에 대해 Exception을 throw(발생)시키면서 throws로 예외 처리를 호출한 곳으로 미룬다

--> main에서 호출했으므로, 이곳에서 try-catch로 예외를 처리

'JAVA 문법' 카테고리의 다른 글

Ch15. 자바 Thread 프로그래밍 (3)  (0) 2021.02.14
Ch15. 자바 Thread 프로그래밍 (1)  (0) 2021.02.14
Ch12. 스트림 (2)  (0) 2021.02.06
Ch12. 스트림 (1)  (0) 2021.02.06
Ch12. 람다식 (2)  (0) 2021.02.06