-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Share] Try-with-resources #5
Comments
이제 봤는데 내용 좋네요 공유 감사해요! |
오 신기하네요. 완전 꿀팁! |
좋은 글 감사합니다!
try (SomeResource resource = getResource()) {
use(resource);
} catch(...) {
...
}
try(Something1 s1 = new Something1();
Something2 s2 = new Something2()) {
...
} catch(...) {
...
}
static String useTry(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
} 위 코드에서 try {
return br.readLine();
} 이 부분( finally {
if (br != null) br.close();
} 이 부분( 그러나 static String useTryResource(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
} 위 코드에서 return br.readLine();
try (BufferedReader br = new BufferedReader(new FileReader(path)))
|
@hihiboss 마지막 3번에서 br.readline() 에러가아니라 new FileReader()의 exception 을 throw하는게 맞지않앙?? |
그리고 다들 봣을수있지만 위의 예제처럼 중첩접근에서의 close() 호출순서에대해서 |
Topic
3장 템플릿 첫 부분에 try-catch가 나와서 참고가 될 만한 try-with-resources에 대해 소개해드리고자 합니다.
Detail
Java를 이용해 외부 자원에 접근하는 경우 한가지 주의해야할 점은 외부자원을 사용한 뒤 제대로 자원을 닫거나 해제해야 한다는 점입니다.
그러나 위 코드에서
fis.close()
도IOException
을 던지기 때문에 다음과 같은 코드가 됩니다.또한
test.txt
파일이 없는 경우는fis
가null
일 것이기 때문에 null check도 해줘야 합니다.코드가 매우 지저분해집니다. 이를 해결하기 위해 JDK 1.7부터는 다음과 같은 인터페이스가 추가되었습니다.
(저자 Josh Bloch는 Effective Java의 저자입니다.)
이 인터페이스 추가와 더불어 try절에 소괄호가 들어가는 문법이 추가되었습니다.
다음과 같이 깔끔하게 코드를 작성할 수 있고,
close()
를 호출하지 않아도 성공적으로 실행했을때나, Exception이 발생했을때 모두 자원을 해제할 수 있습니다.The text was updated successfully, but these errors were encountered: