Organization of java code using try catch finally blocks

I am new to java. I have a question on how to organize Java code when using try catch finally blocks. Suppose I need to read some text files and do some calculations in the contents of a saved file. What should my code look like?

for instance

Code 1 is as follows:

public static void main(String[] args){

try{

//open files using BufferedReader, read and store the file contents.

}catch(IOException e){

e.printStackTrace();

}
finally{

//close the files

}
// do computations on the data
}

Code 2 looks like this:

public static void main(String[] args){

try{

//open files using BufferedReader, read and store the file contents.

// do computations on the data

}catch(IOException e){

e.printStackTrace();

}
finally{

//close the files

}
}

which of the two is the best coding practice? You should also finally block immediately after trying to catch it or you can put it near the end.

+5
source share
5 answers

Use Java 7 and try-with-resources.

try(Connection = pool.getConnection()) { // or any resource you open, like files
// ...

} // auto closes

finally - , , finally . goto , , continue, for, - .

+2

, try-catch. , , ... try-catch, , , .

+1

, , . , .

0

.

, , , , , . , catch , finally.

, catch, - , . , . , if, .

0

, :

1) The file is large . Then you cannot load it into memory. And you should read the file posts one by one and do your logic on each page. This will prevent a memory leak.

2) The file is small . Then you have the choice to follow the first case or read the file in memmory, close it, and then process it.

There is one more consideration : while the file is not closed, other processes cannot access it. This can be a problem if your logic is very long, in which case it is better to read and close the file.

0
source

All Articles