상세 컨텐츠

본문 제목

[JAVA] try-with-resources와 Multi-catch Exceptions

헉!!/jsp, java

by 권태성 2016. 8. 27. 18:31

본문


JAVA8이 나온지도 꽤 시간이 흘럿는데 JAVA에 관심이 없기도하고 회사에서 7을 쓰고있다보니 이제서야 7에 대한 내용을 쓰고있다..


1. try-with-resources

기존에 try-catch 문에서 자원의 해제는 finally문을 만들어서 처리를 했었는데 JAVA 7부터는 그럴 필요가 없다.

public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
            int sales = rs.getInt("SALES");
            int total = rs.getInt("TOTAL");

            System.out.println(coffeeName + ", " + supplierID + ", " + 
                               price + ", " + sales + ", " + total);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    }
}

출처 : oracle docs

위 코드처럼 try문에서 리소스를 생성하면 해당 리소스에 대한 close는 따로 선언해주지 않아도 알아서 처리해준다.

아무것도 안하고 close만 하던 finally를 쓰지 않아도 된다.

(단 AutoClosable, Closeable 인터페이스를 구현한 경우에 한하지만 JAVA7에 포함된 File, Socket 등은 해당 인터페이스가 구현되어있음)


2. Multi-Catch Exceptions

예외 처리를 할 때 항상 exception 별로 catch를 만들어줘야해서 중복코드가 많이 늘어났는데 JAVA 7부터는 여러가지 exception을 한 번에 catch를 할 수 있다.

public class ExampleExceptionHandlingNew

{

   public static void main( String[] args )

   {

    try {

    URL url = new URL("http://www.yoursimpledate.server/");

    BufferedReader reader = new BufferedReader(

    new InputStreamReader(url.openStream()));

    String line = reader.readLine();

    SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");

    Date date = format.parse(line);

    }

    catch(ParseException | IOException exception) {

    // handle our problems here.

    }

   }

}


출처 : oracle technology network

요런 식이다. catch문에 | 으로 구분하여 여러 Exception을 넣어서 처리하는 방법이다.
















관련글 더보기