Language/Java
예외 처리
Jinn
2023. 6. 25. 11:42
예외
- 프로그램 코드에 의해서 수습될 수 있는 미약한 오류
예외 처리
- 프로그램 실행 시 발생할 수 있는 예외의 발생에 대비한 코드를 작성하는 것
- 프로그램의 비정상 종료를 막음

Exception 클래스와 자손 클래스
- 사용자 실수와 같은 외적인 요인에 의해 발생하는 예외
- 예외처리 필수(try-catch)
RuntimeException 클래스와 자손 클래스
- 프로그래머의 실수로 발생하는 예외
- 예외처리 선택
printStackTrace()
- 예외발생 당시의 호출스택에 있던 메서드의 정보와 예외 메시지 출력
getMessage()
- 발생한 예외클래스의 인스턴스에 저장된 메시지를 얻을 수 있다
public class Main {
public static void main(String[] args) {
System.out.println("예외처리 전");
try {
System.out.println(0/0); // 예외 발생
} catch(ArithmeticException ae) {
ae.printStackTrace();
System.out.println("예외 메시지 : " + ae.getMessage()); // 해당 catch 블록 실행
} catch(ArrayIndexOutOfBoundsException ie) {
ie.printStackTrace();
System.out.println("예외 메시지 : " + ie.getMessage());
} catch(Exception e) { // 모든 예외가 처리됨. 마지막 catch 블록으로 지정
e.printStackTrace();
System.out.println("예외 메시지 : " + e.getMessage());
}
System.out.println("예외처리 후");
}
}
// 예외처리 전
// java.lang.ArithmeticException: / by zero
// at Main.main(Main.java:6)
// 예외 메시지 : / by zero
// 예외처리 후
예외 발생시키기 (throw)
public class Main {
public static void main(String[] args) {
System.out.println("프로그램 시작");
try {
// throw new Exception("예외 메시지");
Exception e = new Exception("예외 메시지");
throw e;
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("프로그램 정상 종료");
}
}
// 프로그램 시작
// java.lang.Exception: 예외 메시지
// at Main.main(Main.java:7)
// 프로그램 정상 종료
메서드에 예외 선언하기 (throws)
- 예외처리 떠넘기기
public class Main {
public static void main(String[] args) throws Exception {
method1(); // 3. 예외 넘어옴. JVM 예외처리기로 넘김
}
static void method1() throws Exception {
method2(); // 2. 예외 넘어옴. main으로 넘김
}
static void method2() throws Exception {
throw new Exception("예외 발생"); // 1. 예외 발생. method1로 넘김
}
}
// Exception in thread "main" java.lang.Exception: 예외 발생
// at study_java.ExceptionExercise3.method2(ExceptionExercise3.java:11)
// at study_java.ExceptionExercise3.method1(ExceptionExercise3.java:7)
// at study_java.ExceptionExercise3.main(ExceptionExercise3.java:3)
finally
- 예외 발생여부와 관계없이 수행되어야 하는 코드를 넣는 블록
public class Main {
public static void main(String[] args) {
try {
startInstall();
copyFiles();
} catch(Exception e) {
e.printStackTrace();
} finally {
deleteTempFiles();
}
}
}