Exception
클래스를, 후자는 RuntimeException
클래스를 상속하면 된다.Exception
으로 끝나는 게 관례다. public class XXXException extends Exception {
public XXXException() {}
public XXXException(String message) { super(message); }
}
다음은 보유액 부족 예외 클래스다.
public class RetentionLackException extends Exception {
public RetentionLackException() {
}
public RetentionLackException(String message) {
super(message);
}
}
RetentionLackException
은 Exception
클래스를 상속하고 있기 때문에 컴파일러에 의해 체크된다. 따라서 코드 작성 시 try-catch
블록에 의한 예외 처리가 필요하다.
앞서 선언한 RetentionLackException
은 특수한 경우에 발생하는 예외다.
때문에 원하는 시점에 예외를 발생시켜야 하는데, 예외를 발생시키는 방법은 다음과 같다.
throw new LackOfRetentionException();
throw new LackOfRetentionException("MESSAGE");
try-catch
블록으로 처리할 수도 있지만 throw
하는 것이 일반적이다.다음은 아이템을 구매하는 메소드가 포함된 사용자 클래스다.
public class User {
private long retention = 0;
public long getRetention() { return retention; }
public void setRetention(long retention) { this.retention = retention; }
public void purchase(long price) throws RetentionLackException {
System.out.println("선택하신 상품의 가격은 " + price +"원입니다.");
System.out.println("현재 보유액은 " + retention + "원입니다.");
if(retention < price) {
throw new RetentionLackException("구매 불가 - 보유액 부족: " + (price - retention) + "이 모자랍니다.");
} else {
retention -= price;
System.out.println("구매 성공");
}
}
}
public class Example {
public static void main(String[] args) {
User user = new User();
long price = 3000;
try {
user.purchase(price);
} catch(RetentionLackException e) {
e.printStackTrace();
}
}
}
전달한 오류 메시지와 stack trace가 출력된 것을 확인할 수 있다.
stack trace를 보면 User.java
의 14번째 줄에서 최초로 예외가 발생했고, 그 예외가 Example.java
의 10번째 줄로 떠넘겨졌음을(throw
되었음을) 알 수 있다.