공부 일지/JAVA 공부 일지

자바, 예외 정보 얻기

K◀EY 2021. 4. 13. 16:45

주의 사항!

  • 이 글은 제가 직접 공부하는 중에 작성되고 있습니다.
  • 따라서 제가 이해하는 그대로의 내용이 포함됩니다.
  • 따라서 이 글은 사실과는 다른 내용이 포함될 수 있습니다.


try 블록에서 예외가 발생하면 예외 객체는 catch 블록의 매개 변수에서 참조하게 되므로 매개 변수를 이용하면 예외 객체의 정보를 알 수 있습니다. 모든 예외 객체는 Exception 클래스를 상속하기 때문에 Exception이 가지고 있는 메서드들을 모든 예외 객체에서 호출할 수 있습니다. 그중에서도 가장 많이 사용되는 메서드는 getMessage()와 printStackTrace()입니다.

 

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

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

 

printStackTrace() 메서드는 예외 발생 코드를 추적해서 모두 콘솔에 출력합니다. 어떤 예외가 어디에서 발생했는지 상세하게 출력해주기 때문에 프로그램을 테스트하면서 오류를 찾을 때 활용됩니다.

try {
	//예외 객체 생성
} catch (예외클래스 e) {
	//예외가 가지고 있는 Message 얻기
	String message = e.getMessage();

	//예외 발생의 경로 추적
	e.printStackTrace;
}

 

다음 예제는 Account 클래스를 이용해서 출금을 진행합니다. 그리고 예외 처리 코드에서 BalanceInsufficientException 객체의 getMessage() 메서드와 printStackTrace() 메서드로 예외에 대한 정보를 얻어내고 있습니다.

//BalanceInsufficientException.java
package chapter00.exam00;

public class BalanceInsufficientException extends Exception{
	public BalanceInsufficientException() {}
	public BalanceInsufficientException(String message) {
		super(message);
	}
}
//Account.java
package chapter00.exam00;

public class Account {
	private long balance;
	
	public Account(long balance) {
		this.balance = balance;
	}
	
	public long getBalance() {
		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;
	}
}
//exam00.java
package chapter00.exam00;

public class exam00 
{
	public static void main(String[] args)
	{		
		Account account = new Account(20000);
		
		//출금하기
		try {
			account.withdraw(35000);
		} catch(BalanceInsufficientException e) {
			String message = e.getMessage();
			System.out.println(message);
			System.out.println();
			e.printStackTrace();
		}
	}
}

/*
실행결과

잔고 부족 : 15000원 모자람

chapter00.exam00.BalanceInsufficientException: 잔고 부족 : 15000원 모자람
	at chapter00/chapter00.exam00.Account.withdraw(Account.java:18)
	at chapter00/chapter00.exam00.exam00.main(exam00.java:12)

*/