Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do we mean by "cleanup code"?

Tags:

java

"Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code." what do we mean by "cleanup-type statements" & "cleanup-code"?

like image 253
Anirban Avatar asked Jun 14 '14 04:06

Anirban


1 Answers

As mentioned in the comments, "clean up" means ensuring that any resources (open files, database connections etc) that have been acquired are properly closed or disposed of to prevent resource leaks.

For example:

It's important to close an open Database connection otherwise eventually users might not be able to connect because there are too many open connections that hadn't been properly closed.

Typically you need to execute this code in the finally block of a try/catch block to ensure that the "clean-up" occurs even if exceptions are thrown while the resource is being used.

In modern java (SE 7 and later) you can also use "try with resources" to accomplish the same thing.

Here are links to the official docs for further information:

finally blocks

try with resources

like image 190
Matt Coubrough Avatar answered Sep 18 '22 08:09

Matt Coubrough