Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
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
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter09 : exception 본문

JAVA/chapter19_exception

chapter09 : exception

GAWON 2023. 5. 30. 09:32
package org.joonzis.ex;

/*
 * DepositException		: 마이너스 입금 처리, 예외 코드 1000
 * WithdrawException	: 잔액초과 출금 처리, 예외 코드 2000
 * 						: 마이너스 출금 처리, 예외 코드 2001
 */
class BankAccount{
	// 필드 
	private String no;		// 계좌 번호
	private long balance;	// 계좌 잔액
	
	public BankAccount(String no, long balance) {
		this.no = no;
		this.balance = balance;
	}
	// 입급
	public void deposit(long money) throws DepositException{
		if(money < 0) {
			throw new DepositException(1000,"0보다 작으면 입금 불가!");
		}
		balance += money;
	}
	// 출금
	public void withdraw(long money) throws WithdrawException{
		if(money < 0) {
			throw new WithdrawException(2001, "0보다 작으면 출금 불가!");
		}else if(money > balance) {
			throw new WithdrawException(2000, "잔액보다 크면 출금 불가!");
		}
		balance -= money;
	}
	// 조회
	public void inquiry() {
		System.out.println("계좌 번호 : " + no);
		System.out.println("계좌 잔액 : " + balance);
	}
	// 이체
	public void transfer(BankAccount account, long money) throws DepositException, WithdrawException{
		withdraw(money);
		account.deposit(money);
	}
	
}
class DepositException extends Exception{
	private static final long serialVersionUID = 1L;
	private int errCode;
	public DepositException(int errCode, String msg) {
		super(msg);
		this.errCode = errCode;
	}
	public int getErrCode() {
		return errCode;
	}
}
class WithdrawException extends Exception{
	private static final long serialVersionUID = 1L;
	private int errCode;
	public WithdrawException(int errCode, String msg) {
		super(msg);
		this.errCode = errCode;
	}
	public int getErrCode() {
		return errCode;
	}
}
public class Ex09_exception {
	public static void main(String[] args) {
		
		BankAccount parent = new BankAccount("123-456", 0);
		BankAccount child = new BankAccount("654-321", 0);
		
		try {
			// 1. 부모 계좌에 10,000원 입금 - 입금 예외
			parent.deposit(10000);
			parent.inquiry();
			
			// 2. 부모 계좌에서 5,000원 출금 - 출금 예외
			parent.withdraw(5000);
			parent.inquiry();
			
			// 3. 부모 계좌에서 자식 계좌로 5,000원 이체 - 입금, 출금 예외
			parent.transfer(child, 5000);
			parent.inquiry();
			child.inquiry();
			
		} catch (DepositException e) {
			System.out.println("DepositException 에러 메세지 : " + e.getMessage() +
					"(코드 : " + e.getErrCode() + ")");
		} catch (WithdrawException e) {
			System.out.println("WithdrawException 에러 메세지 : " + e.getMessage() +
					"(코드 : " + e.getErrCode() + ")");
		}
		
		
		
		
	}
}

'JAVA > chapter19_exception' 카테고리의 다른 글

Test . exception  (0) 2023.05.30
chapter08 : exception  (0) 2023.05.30
chapter07 : exception  (0) 2023.05.30
chapter06 : exception  (0) 2023.05.30
chapter05 : exception  (0) 2023.05.30