[이것이 자바다] 11장 정리

이 포스트는 자바 예외 처리에 대한 예제 코드를 통해 익셉션 클래스를 커스텀하고, throws 키워드를 사용하여 예외를 떠넘기는 방법을 소개합니다.
Jan 15, 2024
[이것이 자바다] 11장 정리

InsufficientException.java

package ch11; public class InsufficientException extends Exception { public InsufficientException() { } public InsufficientException(String message) { super(message); // 익셉션 객체의 공통 메소드인 getMessage의 리턴값으로 사용하기 위해 예외 메시지를 입력받는 생성자 선언 } }

Account.java

package ch11; public class Account { private long balance; public Account() { } public long getBalance() { return balance; } public void deposit(int money) { balance += money; } public void withdraw(int money) throws InsufficientException { // 호출한 곳으로 예외 떠넘김 if (balance < money) { throw new InsufficientException("잔고 부족: " + (money - balance) + " 모자람"); } } }

AccountExample.java

package ch11; 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 (InsufficientException e) { // 예외 처리 코드와 함께 withdraw() 메소드 호출 String message = e.getMessage(); System.out.println(message); } } }
 

핵심 키워드

  • extends Exception 를 통해 익셉션 클래스를 커스텀할 수 있다.
    • 기본 생성자를 생성하고, 익셉션 객체의 공통 메소드인 getMessage의 리턴값으로 사용하기 위해 예외 메시지를 입력받는 생성자를 선언한다.
  • throws 키워드는 예외 발생시 호출했던 곳으로 예외를 떠넘긴다.
 

결론

해당 문제를 풀면서 예외와 버그, 논리적 오류에 대한 차이점을 이해할 수 있었다.
Share article
RSSPowered by inblog