개념
public void method1(){
try {
method2(); // throws가 붙은 method2는 반드시 이렇게 try문 안에서 호출되어야 함.
// method2가 떠넘긴 예외를 아래 catch문을 통해 처리해 주고 있다.
}
catch (ClassNotFoundException e1) {
System.out.println("클래스가 존재하지 않음.");
}
public void method2() throws ClassNotFoundException {
Class clazz = Class.forName("java.lang.String22");
}
구성
try{
} catch(예외1){
} catch(예외2){
}
예시 --> exception 객체 생성 어떻게 응용?
int c;
try {
c = 4 / 0;
} catch(ArithmeticException e) { // <-- 예외 객체 생성
c = -1; // 예외가 발생하여 이 문장이 수행된다.
}
예외 클래스 종류
finally
exception 구분
throw(예외 던지기) --> throw 활용?
예외 처리 방법
예외 복구
int maxretry = MAX_RETRY;
while(maxretry -- > 0) {
try {
// 예외가 발생할 가능성이 있는 시도
return; // 작업성공시 리턴
}
catch (SomeException e) {
// 로그 출력. 정해진 시간만큼 대기
}
finally {
// 리소스 반납 및 정리 작업
}
}
throw new RetryFailedException(); // 최대 재시도 횟수를 넘기면 직접 예외 발생
예외 처리 회피
public void add() throws SQLException {
... // 구현 로직
}
개발자가 직접 정의하여 만드는 예외(두가지 방식으로 만들 수 있음)
public class AnyCreateException extends Exception { // <-- 이런 식으로 상속
public AnyCreateException() {};
public AnyCreateException(String message) {
super(message);
// 사용자 정의 예외의 생성. 생성자는 보통 두 가지를 선언하는데
// 두 번째의 경우 에외 메시지를 전달하기 위해 String 타입의 매개 변수를 갖는 생성자이다.
}
}
.....
public class Account{
int balance = 100;
public void withdraw(int money) throws AnyCreateException {
if(balance < money){
throw new AnyCreateException("Excpetion 발생!");
// AnyCreateException 의 두 번째 생성자를 선택한 것이다.
// 모든 예외는 Exception이 가지고 있는 메소드들을 호출 할 수 있다.
// 그 중 getMessage 메소드가 이 예외 메시지를 리턴한다. 사용은 아래에 구현했다.
}
}
....
public static void main(String[] args){
Account account = new Account();
try{
account.wtihdraw(30000);
}
catch ( AnyCreateException e ) {
String message = e.getMessage(); // 메시지를 담은 생성자를 선택했을 때, 그 메시지를
// getMessage() 메소드가 리턴한다.
System.out.println(message);
e.printStackTrace(); // 예외가 어디에서 발생했는지 출력해준다.
}