try-catch-finally와try-with-resources

1071 단어
Java 개발 초실용 100편:https://blog.csdn.net/libusi001/article/details/100086670
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

코드

@Test
public void test4() {
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream("D:\\head.jpg");
        // do something
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

새로 쓰기

@Test
public void test5() {
    try (InputStream inputStream = new FileInputStream("D:\\head.jpg")) {
        byte[] bytes = inputStream.readAllBytes();
        // do something
    } catch (IOException e) {
        e.printStackTrace();
    }
}

try-with-resources의 사용법은try 키워드 뒤에 괄호를 따라 닫아야 할 자원을 괄호 안에 정의하는 것이다.try 블록이 실행된 후에 자동으로 자원을 방출합니다.
 
도움이 되면 좋아요를 눌러서 좋은 습관을 기르세요!
질문, 소통, 격려, 댓글 남겨주세요!

좋은 웹페이지 즐겨찾기