예외처리 1) 정의 : 프로그램 실행 시 발생할 수 있는 예외의 발생에 대비한 코드를 작성하는 것 2)목적 : 프로그램의 비정상 종료를 막고, 정상적인 실행상태를 유지하는 것
구조
try {
// 예외가 발생할 수 있는 코드
} catch (ExceptionType1 e1) {
// ExceptionType1에 대한 예외 처리
} catch (ExceptionType2 e2) {
// ExceptionType2에 대한 예외 처리
} catch (ExceptionType3 e3) {
// ExceptionType3에 대한 예외 처리
}
ch8-5 try-catch문에서의 흐름
- try 블럭 내에서 예외가 발생한 경우, 1. 발생한 예외와 일치하는 catch 블럭이 있는지 확인 2. 일치하는 catch 블럭을 찾게 되면, 그 catch 블럭 내의 문장들을 수행하고 전체 try-catch 문을 빠져나가서 그 다음 문장을 계속해서 수행한다. 만일 일치하는 catch블럭을 찾지 못하면, 예외는 처리되지 못한다.
- try블럭 내에서 예외가 발생하지 않는 경우 1. catch블럭을 거치지 않고 전체 try-catch 문을 빠져나가서 수행을 계속한다.
예외가 발생하지 않을 떄
public class Ex8_1 { // 예외 발생하지 않았을 떄
public static void main(String[] args) {
System.out.println(1);
try{
System.out.println(2);
System.out.println(3);
}catch (Exception e){
System.out.println(4);
}// try - catch의 끝
System.out.println(5);
}
}
예외가 발생하였을 때
public class Ex8_2 {
public static void main(String[] args) {
System.out.println(1);
try {
System.out.println(0 / 0); // 예외 발생
System.out.println(2);
} catch (ArithmeticException e) {
System.out.println(3);
} // try-catch 끝
System.out.println(4);
}
}
ch8-6 예외의 발생과 catch블럭
예외가 발생하면, 이를 처리할 catch블럭을 찾아 내려감
public class Ex8_4 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0 / 0); // 예외 발생
System.out.println(4); // 실행되지 않는다.
} catch (ArithmeticException ae) {
// 예외가 ArithmeticException인 경우
System.out.println("ArithmeticException");
} catch (Exception e) {
// 다른 예외가 발생한 경우
System.out.println("Exception");
} // try-catch 끝
System.out.println(6); // 예외 처리 후 계속 실행
}
}
Exception은 모든 예외의 최고 조상이다.
public class Ex8_4 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0 / 0); // 예외 발생
System.out.println(4); // 실행되지 않는다.
} catch (Exception e) {
// 다른 예외가 발생한 경우
System.out.println("Exception");
} // try-catch 끝
System.out.println(6); // 예외 처리 후 계속 실행
}
}
이러한 처리도 가능하다.
알맞는 예외가 없을 경우
public class Ex8_4 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(args[0]); // 예외가 ArrayIndexOutOfBoundsException 경우
System.out.println(4); // 실행되지 않는다.
} catch (ArithmeticException ae) {
System.out.println("ArithmeticException");
}
System.out.println(6);
}
}
예외 처리가 안되서 비정상 종료
public class Ex8_4 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(args[0]); // 예외가 ArrayIndexOutOfBoundsException 경우
System.out.println(4);
} catch (ArithmeticException ae) {
System.out.println("ArithmeticException");
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
System.out.println(6); // 예외 처리 후 계속 실행
}
}