- 에러 : 프로그램 코드에 의해 수습될 수 없는 심각한 오류
- 예외 : 프로그램 코드에 의해서 수습될 수 있는 다소 미약한 오류
1. try-catch
- 예외처리를 통해서 프로그램이 비정상적으로 종료되는 것을 방지할 수 있다.
- 모든 예외는 Exception클래스의 자식 클래스이다.
- RuntimeException클래스와 그 자식들은 예외처리가 강제되지 않는다.
- [RuntimeException클래스와 그 자식들을 제외한]Exception클래스의 자식들은 예외처리가 강제된다.
- try{ } catch(Exception e) { } : try블럭 안의 내용을 실행 중 예외가 발생하면 catch로 넘어간다.
- catch의 파라미터로는 처리할 예외를 지정해준다.
- 파라미터로 지정한 예외와 일치한 예외가 발생되면 catch블럭 안의 내용이 수행된 후 try-catch를 빠져나간다.
- 지정한 예외와 일치하는 catch가 없을 경우 예외는 처리되지 않는다.
try {
int result = 10 / 0;
System.out.println(result);
}catch(ArithmeticException | IndexOutOfBoundsException e) {
e.printStackTrace();
}catch(NullPointerException e) {
}catch(Exception e) {
}
- 보통 catch의 파라미터로 자식클래스의 예외를 넣지않고 Exception클래스를 지정해 사용
2. throwException
throw new Exception( );
- 예외를 발생시키는 명령어
- 예외가 어떻게 발생되는지 상황을 테스트할때 사용
try {
throw new IOException();
} catch(Exception e) {
e.printStackTrace();
}
3. throwsException
void method( ) throws Exception{ }
- 메서드 호출시 발생할 수 있는 예외를 선언
- 예외를 선언하면 예외처리를 하지 않고 자신을 호출한 메서드로 예외처리를 넘겨준다.
try {
method();
} catch (IOException e) {
e.printStackTrace();
}
private static void method() throws IOException {
}
4. 자주 발생하는 예외
1. NullPointerException : null을 참조했을때 발생
String str = null;
System.out.println(str.equals("abc"));
2. ArrayIndexOutOfBoundsException : 배열 인덱스의 범위를 벗어났을때 발생
int[] arr = new int[10];
for(int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]);
}