문제(예외)가 발생해도 프로그램이 중간에 멈추지 않게 처리하는 것
예외 처리 방법
1) Exception이 발생한 곳에서 직접 처리
try ~ catch문을 이용하여 예외 처리하기
ex)
public void method() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("입력 : ");
String str = br.readLine();
System.out.println("입력된 문자열 : " + str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
System.out.println("BufferedReader 반환");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2) Exception 처리를 호출한 메소드에게 위임
메소드 선언 시 throws Exception명을 추가하여 호출한 상위 메소드에게 처리를 위임한다. 계속 위임하면 main( ) 메서드 까지 위임하게 되고 거기서도 처리되지 않는 경우 프로그램이 비정상 종료된다.
ex)
public static void main(String[] args) {
ThrowsTest tt = new ThrowsTest();
try {
tt.methodA();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("프로그램 종료");
}
}
public void methodA() throws IOException {
methodB();
}
public void methodB() throws IOException {
methodC();
}
public void methodC() throws IOException {
throw new IOException(); // IOException 강제 발생
}
오버라이딩 시 예외(throws) 방법