목차
에러와 예외
어떤 원인에 의해 오동작하거나 비정상적으로 종료되는 경우
Error
메모리 부족, stack overflow와 같이 일단 발생하면 복구할 수 없는 상황
프로그램의 비정상적 종료를 막을 수 없음 → 디버깅 필요
Exception
읽으려는 파일이 없거나, 네트워크 연결이 안 되는 등 수습될 수 있는 비교적 상태가 약한 것들
프로그램 코드에 의해 수습될 수 있는 상황
예외처리란?
- 예외 발생 시 프로그램의 비정상 종료를 막고 정상적인 실행 상태를 유지하는 것
- 예외의 감지 및 예외 발생 시 동작할 코드 작성 필요
예외 처리 키워드
try-catch
try {
// 예외가 발생할 수 있는 코드
} catch (Exception e) {
// 예외가 발생했을 때 처리할 코드
}
// try-catch 블록이 끝난 후 실행
try ~ catch ~ finally
finally는 예외 발생 여부와 상관 없이 언제나 실행
중간에 return을 만나는 경우도 finally 블록을 먼저 수행 후 return 실행
주로 자원을 반납/반환할 때 사용, 항상 실행되어야 하는 기능
try-catch 블록 밖에다가 써도 되지만, try 구문 안에 return이 있으면 해당 코드가 실행되지 않을 수 있고 통일성이 없어 보임
try {
System.out.println("1");
int i = 1 / num;
// int i = 1 / 0;
System.out.println("2");
return;
} catch (ArithmeticException e) {
System.out.println("3");
} finally {
System.out.println("4");
}
System.out.println("5"); // 에러 발생x, return -> 실행X // 에러 발생o, returnx -> 실행o
1. int i= 1 / num;
에러 발생X - 1 2 4 출력
2. int i = 1 / 0;
에러 발생O - 1 3 4 5 출력
다중 exception handling
try 블록에서 여러 종류의 예외가 발생한 경우
하나의 try 블록에 여러 개의 catch 블록 추가 가능 (예외 종류 별로)
유의사항
- JVM이 던진 예외는 catch 문장을 찾을 때는 다형성이 적용
- Exception > XXException 상속 관계
- 상속 타입의 예외가 먼저 선언되는 경우 뒤에 등장하는 catch 블록은 동작x
- 상속 관계가 없는 경우는 무관
- 상속 관계에서는 작은 범위(자식)에서 큰 범위(조상)순으로 정의
Exception은 모든 예외 class의 조상 → Exception이 다 처리할 수 있음
try {
System.out.println(nums[2]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// Array~~와 arithmetic~~은 상속 관계가 아니라 상관X
// Exception은 가장 마지막에 정의
throw: 처리 위임
method에서 처리해야 할 하나 이상의 예외를 호출한 곳으로 전달 (처리 위임)
예외가 없어지는 것이 아니라 단순히 전달됨
예외를 전달받은 메서드는 다시 예외 처리의 책임 발생
Checked Exception
- 예외에 대한 대처 코드가 없으면 컴파일이 진행되지 않음
- 반드시 try ~ catch 또는 throws 필요, 필요한 곳에서 try~catch 처리
UnChecked Exception
- 예외에 대한 대처 코드가 없더라도 컴파일은 진행됨
- throws하지 않아도 전달 O, 결국은 try~catch로 처리해야 함 → 실수 가능성 높음
메서드 재정의와 throws
메서드 재정의시 조상 클래스가 던지는 예외보다 부모 예외를 던질 수 없다.
class Parent {
void methodA() throws IOException {
}
void methodB() throws ClassNotFoundException {
}
}
public class OverridingTest extends Parent {
@Override
void methodA() throws FileNotFoundException {
}
@Override
void methodB() throws Exception {
}
}
methodA는 FileNotfoundException이 IOException을 상속 → 가능
methodB는 Exception이 ClassNotFoundException의 부모 예외이므로 불가능
사용자 정의 예외
API에 정의된 exception 이외에 필요에 따라 사용자 정의 예외 클래스 작성
대부분 Exception 또는 RuntimeExcepton 클래스를 상속받아 작성
- check Exception 활용: 명시적 예외 처리 또는 throw 필요
- (코드는 복잡하지만 오류 발생 가능성 down)
- runtime Exception 활용: 묵시적 예외 처리 가능
- (코드는 간결하지만 예외 처리, 누락 가능성 발생)
장점
- 객체의 활용: 필요한 추가 정보, 기능 활용
- 코드의 재사용: 동일한 상황에서 예외 객체 재사용 가능
- throws 메커니즘의 이용: 중간 호출 단계에서 return 불필요
'Java' 카테고리의 다른 글
[백준] 2023 - 신기한 소수 (자바 Java) (0) | 2022.12.25 |
---|---|
[백준] 10986 - 나머지 합 (자바/Java) (0) | 2022.09.27 |
[자바/Java] 직렬화와 역직렬화, ObjectInputStream ObjectOutputStream, Serializable (0) | 2022.07.28 |
[자바/Java] 객체 참조 시 인터페이스 사용 이유 (0) | 2022.07.28 |
[자바/Java] 제네릭 Generics (0) | 2022.07.27 |