Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> How is a try-with-resources not guaranteed? At least in Java, it is guaranteed to run

There's a subtle detail you have to be careful with, however: if you try to allocate memory or call a method between allocating your resource and actually doing the try-with-resources, you might get an OutOfMemoryError or a StackOverflowError, and your resource will leak. That is, if you do something like:

  try (MyHolder holder = new MyHolder(allocateResource())) { ... }
You can have a leak if the memory allocation in the "new MyHolder()" fails, or if there's not enough space in the stack to call the MyHolder constructor.

> plus, you can get your closing/destructor logic wrong in RAII languages as well.

For instance, in C++ you can accidentally put your resource in a temporary which is immediately destructed at the end of the line, when you wanted it to last until the end of the enclosing scope. Rust makes it harder for this to happen, but it's still possible.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: