/ JAVA

객체지향 프로그래밍 복습 (9) Exception Handling

[JAVA] 객체지향 프로그래밍 복습 (9) Exception Handling

자바(Java)는 C언어에 객체 지향적 기능을 추가하여 만든 C++과는 달리, 처음부터 객체 지향 언어로 개발된 프로그래밍 언어입니다. 자바는 자바 가상 머신(JVM, Java Virtual Machine)을 사용하여, 운영체제와는 독립적으로 동작할 수 있습니다. 따라서 자바는 어느 운영체제에서나 같은 형태로 실행될 수 있습니다. 바로 이러한 점이 수많은 개발자로 하여금 자바를 사용하게 하는 원동력이 되고 있습니다. 현재 자바는 전 세계에서 가장 많이 사용하는 프로그래밍 언어 중 하나입니다.

예외처리 Exception Handling

프로그램을 만들다 보면 수없이 많은 에러가 납니다. 물론 에러가 나는 이유는 프로그램이 오동작을 하지 않기 하기 위한 자바의 배려입니다. 하지만 때로는 이러한 에러를 무시하고 싶을 때도 있고, 에러가 날 때 그에 맞는 적절한 처리를 하고 싶을 때도 있습니다. 이에 자바는 try … catch, throw등을 이용하여 에러를 처리 할 수 있도록 도와줍니다. 예외를 처리하는 방법에 대해서 알게 되면 보다 안전하고 유연한 프로그래밍을 구사 할 수 있을 것입니다.

계좌, 출금 클래스

예외 처리를 복습하기 위해 예외가 발생하게끔 계좌 클래스와 출금 클래스를 구현합니다.

  • BankAccount
    • 계좌 번호
    • 주인 이름
    • 계좌 개설 날짜
    • 현재 금액
    • 대출 가능 금액
    • 현재 대출 금액
  • WithdrawException
    • Exception 클래스 상속

BankAccount.java

import java.util.Date;

public class BankAccount {
	private String accountNumber;
	private String holderName;
	private Date dateOpened;
	private int balance;			//현재 계좌 금액
	private int loanLimit;			//대출 가능 금액
	private int loanBalance;		//현재 대출 금액

	public BankAccount(String acct, String name, int bal, int loanLimit) {
		this.accountNumber = acct;
		this.holderName = name;
		this.balance = bal;
		this.loanLimit = loanLimit;
		this.loanBalance = 0;
		Date today = new Date();
		this.dateOpened = today;
	}

	public int deposit(int amount) {
		return balance+=amount;
	}

	public int withdraw(int amount) throws WithdrawException {
		if(amount <= this.balance) {
			this.balance -= amount;
			return this.balance;
		}
		else {
			int needs = amount - this.balance;
			int affordableLoan = this.loanLimit - this.loanBalance;
			if(needs <= affordableLoan) {
				this.balance = 0;
				this.loanBalance += needs;
				return this.balance;
			} 
			else {
				needs -= affordableLoan;
				throw new WithdrawException("잔액 및 대출 가능 금액이 부족합니다. \n부족 금액: "+needs, needs, affordableLoan);
			}

		}

	}

	public void printInfo() {
		System.out.println("Account Number: " + this.accountNumber);
		System.out.println("Curreny Balance: " + this.balance);
		System.out.println("Loan Limit: " + this.loanLimit);
		System.out.println("Loan Balance: " + this.loanBalance + "\n");
	}
}

WithdrawException. java

public class WithdrawException extends Exception{
	private String exceptionMessage;
	private int amountShortage;
	private int amountFromLoan;
	
	public WithdrawException(String msg, int amtS, int amtF) {
		this.exceptionMessage = msg;
		this.amountShortage = amtS;
		this.amountFromLoan = amtF;
		
		System.out.println(msg);
	}
	
	public int getAmountShortage() {
		return this.amountShortage;
	}
	
	public int getAmountFromLoan() {
		return this.amountFromLoan;
	}
}

test.java

public class TestProgram {

	public static void main(String[] args) {
		BankAccount a1 = new BankAccount("111-222-333", "John Smith", 2000, 1000); 
		
		System.out.println("1000 입금합니다.");
		a1.deposit(1000);
		a1.printInfo();
		
		try {
			System.out.println("3000 출금합니다.");
			a1.withdraw(3000);
		} catch(WithdrawException e) {
		}
		a1.printInfo();
		
		System.out.println("500 입금합니다.");
		a1.deposit(500);
		a1.printInfo();
		
		try {
			System.out.println("1000 출금합니다.");
			a1.withdraw(1000);		
		} catch(WithdrawException e) {
		}
		a1.printInfo();	
		
		try {
			System.out.println("2000 출금합니다.");
			a1.withdraw(2000);	
		} catch(WithdrawException e) {
		}
		a1.printInfo();
		
		try {
			System.out.println("500 출금합니다.");
			a1.withdraw(500);
		} catch(WithdrawException e) {
		}
		a1.printInfo();
	}

}

결과