연습문제
BankException
마이너스 입금 불가, 코드값 1000
마이너스 출금 불가, 코드값 2000
잔액보다 큰 출금 불가, 코드값 2001
deposit() throws BankException
sithdrawal() throws BankException
transfer() throws BankException
Bank 클래스
public class Bank { private String accNo; private long balance; public Bank(String accNo, long balance) { super(); this.accNo = accNo; this.balance = balance; } public void deposit(long money) throws BankException { if(money < 0) { throw new BankException("마이너스 입금 불가", 1); } balance += money; } public long withdrawal(long money) throws BankException { if(money < 0) { throw new BankException("마이너스 출금 불가", 2); } else if(balance < money) { throw new BankException("잔액 부족", 3); } balance -= money; return money; } public void transfer(Bank acc, long money) throws BankException { acc.deposit(withdrawal(money)); } public void inquiry() { System.out.println(this); } @Override public String toString() { return "Bank [accNo=" + accNo + ", balance=" + balance + "]"; } }
BankException 클래스
public class BankException extends Exception { private static final long serialVersionUID = -3990936769640382913L; private int errorCode; public BankException(String message, int errorCode) { super(message); this.errorCode = errorCode; } public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } }
Main 클래스
public class Main { public static void main(String[] args) { Bank me = new Bank("1111", 10_000); Bank mom = new Bank("2222", 100_000); try { mom.transfer(me, 50_000); } catch (BankException e) { System.out.println(e.getMessage() + "," + e.getErrorCode()); } me.inquiry(); mom.inquiry(); } }
출력:
Bank [accNo=1111, balance=60000]
Bank [accNo=2222, balance=50000]
public static void main(String[] args) throws BankException {