Why do I need to use finally to close resources?

南楼画角 提交于 2019-11-28 01:20:37

Because garbage collection is not the same thing as resource cleanup.

For example, if you have a JDBC Connection object that goes out of scope, there's no signal sent to the database server to indicate that open cursors and connections are no longer needed. Without those messages, you'll eventually exhaust the number of cursors and connections available to you.

Same with file handles and any other resource. Clean up after thyself.

Well you've given a bad example - I suspect you meant something like FileInputStream - but the basic reason is that Java doesn't have deterministic finalization.

The scope of the variable f ends with the block it's declared in (not the try block), but that doesn't mean there are necessarily no "live" references to the object any more - and the garbage collector will neither finalize the object nor garbage collect it in any deterministic manner.

Unless you want to leave resources hanging around for an arbitrary length of time (and delay garbage collection, as finalizers require an extra round of collection before the memory is finally released), you should explicitly close resources.

Basically Java does not support RAII in the same way that C++ does; you shouldn't try to use it as if it were C++.

because finally is called everytime, even if you get an exception raised. the finally block insure you that the file/connection will be closed.

The reason is that Java doesn't guarantee that an object will be garbage-collected as soon as a particular reference to it falls out of scope. So for objects that reference limited system resources, such as a file descriptor, it's not enough to wait for garbage collection.

Note though, that java.io.File is not actually such an object.

We handled exception by try catch finally ,finally block every time execute but there is no guarantee of catch because catch block execute only if exception passed in parameter matched. For example if we have open any database connection so it is must we closed it before leave,tht must be implemented into finally.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!