Error 와 Exception의 차이점에 대해 알아봤다. Exception의 unchecked 예외가 Error와 같은 오류인 걸 알았다.
| Key | Error | Exception |
|---|---|---|
| 타입 | unchecked 예외 | unchecked 예외 + checked 예외 |
| 패키지 | java.lang.error | java.lang.Exception |
| 복구 | 불가능 | 가능 |
| 발생 | 런타임 | 런타임 + 컴파일 타임 |

| Checked Exception | Unchecked Exception | |
|---|---|---|
| 처리여부 | 반드시 예외를 처리해야 함 | 명시적인 처리를 강제하지 않음 |
| 확인시점 | 컴파일 단계 | 실행단계 |
| 예외발생시 트랜잭션 처리 | roll-back 하지 않음 | roll-back 함 |
| 대표 예외 | Exception의 상속받는 하위 클래스 중 | Runtime Exception를 상속받는 하위 클래스이다. |
| Runtime Exception을 제외한 모든 예외 | NullPointerException, IllegalArgumentException | |
| IOException, SQLException | IndexOutOfBoundExceptoin, SystemException |
💡 Unchecked Exception은 보통 개발자의 실수로 인한 에러라고 한다.
import java.sql.DriverManager;
import java.sql.SQLException;
public class OracleEx01 {
public static void main(String args[])
{
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
String name;
String street;
String city;
Scanner scan = new Scanner(System.in);
System.out.println("사원이름 : ");
name = scan.nextLine();
System.out.println("거리 : ");
street = scan.nextLine();
System.out.println("도시 : ");
city = scan.nextLine();
try {
String query = "insert into employee values ('" +name+ "', '" +street
+ "', '"+ city + "')";
conn = DBHelper.getConnection();
pstm = conn.prepareStatement(query);
rs = pstm.executeUpdate();
System.out.println("============================================");
System.out.println("추가되었습니다. -> ('" +name+ "', '" +street + "', '"+ city + "')");
} catch (SQLException sqle) {
System.out.println("예외 발생");
sqle.printStackTrace();
}finally{
//if ( rs != null ){rs.close();} //처음엔 try-catch로 감싸지지 않았다.
//if ( pstm != null ){pstm.close();}
//if ( conn != null ){conn.close();}
try{ // try-catch로 예외처리를 해주었다.
if ( rs != null ){rs.close();}
if ( pstm != null ){pstm.close();}
if ( conn != null ){conn.close();}
}catch(Exception e){
throw new RuntimeException(e.getMessage());
}
}
}
}
오라클 DB에서 JDBC 든 무엇이든 DB 연결은 결국 소켓 통신이다. 커넥션을 만들고 close를 하지 않으면, 커넥션 하나하나마다 각각의 세션이 생성이 된다. 이 세션이 DB 서버의 메모리공간을 2~3kb 정도 차지한다고 한다. 그래서 close를 하지않으면 이것이 누적되어 결국 가득 차버리게 되면 메모리 누수현상이 발생하여 서버가 멈춰버리게 된다. 따라서 DB를 사용할때는 연결하고 닫아주는 작업을 해줘야한다. 그래서 try-catch를 해서 예외처리를 해주지않아 if문에 걸려 빠져버리면 나머지는 닫히지 않고 에러가 나버린다. 그래서 try-catch문으로 감싸줘서 어떤 RuntimeException이 발생되면, 원하는 흘름대로 진행되지 않고 튕겨 나가게 했다. 즉, 닫히지 않고 튕기지만 메세지를 받을 수 있다. 자세한 건 더욱 알아봐야겠다.
예외 클래스의 구조 그림 출처 : https://www.nextree.co.kr/p3239/