Java/10. 예외 처리 (Exception)

Day 14 : 예외 정보 얻기

pancakemaker 2021. 11. 5. 18:49

예외 메시지는 다음과 같이 catch 블록에서 getMessage() 메소드의 리턴값으로 얻을 수 있음

} catch(XXXException e) {
	String message = e.getMessage();
}

 

사용자 정의 예외 발생시키기

package sec07_user_define_exception;

public class Account {
	//필드
	private long balance;
	
	//생성자
	public Account() {}
	
	//메소드
	public long getBalance() { //money값이 누적된 balance를 불러와서 balance 필드에 저장  
		return balance;
	}
	
	public void deposit(int money) { //입금
		balance += money;
	}
	
	public void withdraw(int money) throws BalanceInsufficientException { //출금
		if(balance < money) { //잔고가 출금액보다 적을 경우
			throw new BalanceInsufficientException("잔고부족: " + (money-balance) + " 모자람");
		} //잔고가 출금액보다 같거나 많을경우
		balance -= money;
	}
}
package sec07_user_define_exception;

public class AccountExample {
	public static void main(String[] args) {
		Account account = new Account();
		
		//예금하기
		account.deposit(10000);
		System.out.println("예금액: " + account.getBalance());
		
		//출금하기
		try {
			account.withdraw(30000);
		} catch (BalanceInsufficientException e) {
			String message = e.getMessage();
			System.out.println(message);
			//e.printStackTrace(); //오류가 난 위치를 추적해서 출력
		}
		
	}
}
예금액: 10000
잔고부족: 20000 모자람