예외처리 ExceptionJava2022. 12. 9. 21:19
Table of Contents
728x90
728x90
예외처리(Exception)
- 오류가 났을 때 try catch, throw를 이용하여 오류를 처리하는 것
- 오류가 발생하면 프로그램이 비정상적으로 종료되지만, 예외처리 추가 시 정상적인 실행상태로 되돌릴 수 있다
- 예외처리를 통해 사용자 입장에서 생각하여 사용자가 할 법한 실수들을 대비
- Exception : 프로그램 실행도중 종료될 수 있는 문제와 연관되어 예외처리를 선택적으로 하거나 꼭 해야하는 클래스들의 최상위 클래스
- Error 클래스 : 프로그램 실행 도중 해결할 수 있는 문제가 아니라 이후 발견되어 처리해야하는 문제들이 연관되어 있는 클래스
예외가 발생하는 순간들
System.out.println(10/0); // ArithmeticException
int[] arr = {1,2,3};
System.out.println(arr[3]); // ArrayIndexOutOfBoundsException
try~catch를 이용한 예외처리
try{
System.out.println(10/0);
} catch(Exception e){
System.out.println("0으로 나누지마세요");
}
// Console
0으로 나누지마세요
try문 안에서 코드가 실행되다가 예외가 발생하는 행에서 즉시 catch안의 문장을 실행한다
try{
int[] arr = {1,2,3};
System.out.println(arr[3]);
System.out.println("배열 실행 완료"); // 실행되지 않는다
} catch(Exception e) {
System.out.println("없는 배열 불러내지마세요");
}
// Console
없는 배열 불러내지마세요
예외가 발생해도 반드시 실행되어야 하는 부분이 있다면 finally를 이용한다
try{
int[] arr = {1,2,3};
System.out.println(arr[3]);
System.out.println("배열 실행 완료"); // 실행되지 않는다
} catch(Exception e) {
System.out.println("없는 배열 불러내지마세요");
} finally {
System.out.println("배열 실행 완료"); // 예외처리가 되어도 무조건 실행
}
// Console
없는 배열 불러내지마세요
배열 실행 완료
예외 던지기 (throws)
- 강제로 예외를 발생시키고 싶을 때 사용
- Throwable : 모든 에러, 예외의 최상위 클래스
- 메서드를 호출한 곳에서 예외를 처리하라고 떠넘기는 것
- 호출한 곳에서는 반드시 예외처리 관련 코드가 필요하다
- 예외를 발생시키는 키워드는 throw이고 메서드에 선언하는 키워드는 throws이다
// throw를 이용하여 예외를 떠넘겼지만 코드 길이가 길어지고 가독성이 좋지 않음
public class Except {
public static void main(String[] args) {
exam1();
exam2();
exam3();
}
public static void exam1() {
try {
throw new ArrayIndexOutOfBoundsException("에러");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
public static void exam2() {
try {
throw new ArithmeticException("에러");
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
public static void exam3() {
try {
throw new NullPointerException("에러");
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
// 자신을 호출한 메서드에게 예외를 전달하여 예외 처리를 떠맡긴다
public class Except {
public static void main(String[] args) {
try{
exam1();
exam2();
exam3();
}catch(ArrayIndexOutOfBoundsException | ArithmeticException | NullPointerException e) {
System.out.println(e.getMessage());
}
}
public static void exam1() throws ArrayIndexOutOfBoundsException{
throw new ArrayIndexOutOfBoundsException("에러");
}
public static void exam2() throws ArithmeticException{
throw new ArithmeticException("에러");
}
public static void exam3() throws NullPointerException{
throw new NullPointerException("에러");
}
}
exam1에서 에러가 나게되면 아래의 exam2와 exam3 메서드는 호출되지 않는다
>> 어디에 사용하는지. 어디서 throw를 통해 넘기는지가 중요하다
// Console
에러
getMessage :에러의 원인만을 출력
toString : 에러의 Exception내용과 원인 출력
printStackTrace : 에러의 발생 근원지를 찾아 단계별로 에러 출력
728x90
300x250
@mag1c :: 꾸준히 재밌게
2023.04 ~ 백엔드 개발자의 기록
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!