예외 처리

송현진·2023년 4월 8일

Java

목록 보기
1/11
post-thumbnail

ErrorException의 차이점에 대해 알아봤다. Exceptionunchecked 예외가 Error와 같은 오류인 걸 알았다.

KeyErrorException
타입unchecked 예외unchecked 예외 + checked 예외
패키지java.lang.errorjava.lang.Exception
복구불가능가능
발생런타임런타임 + 컴파일 타임

예외 클래스의 구조

Checked Exception과 Unhecked Exception에 대해 알아봤다

Checked ExceptionUnchecked Exception
처리여부반드시 예외를 처리해야 함명시적인 처리를 강제하지 않음
확인시점컴파일 단계실행단계
예외발생시 트랜잭션 처리roll-back 하지 않음roll-back 함
대표 예외Exception의 상속받는 하위 클래스 중Runtime Exception를 상속받는 하위 클래스이다.
Runtime Exception을 제외한 모든 예외NullPointerException, IllegalArgumentException
IOException, SQLExceptionIndexOutOfBoundExceptoin, SystemException

💡 Unchecked Exception은 보통 개발자의 실수로 인한 에러라고 한다.

try-catch-finally문인데 자꾸 닫히지 않고 에러가 나서 코드를 하나씩 보면서 이해해보았다.
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/

profile
개발자가 되고 싶은 취준생

0개의 댓글