Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

organizing java code when using try catch finally blocks

i am a java newbie. i have a question regarding how to organize java code when using try catch finally blocks. suppose i have to read some text files and do some computations on the stored file contents. how should my code look like?

For example

code 1 looks like:

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:

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 a better coding practice? Also should finally block be placed just after try catch or it can be placed towards the end.

like image 709
scv Avatar asked Oct 22 '22 15:10

scv


1 Answers

Use Java 7 and try-with-resources.

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

} // auto closes

This feature comes close to deprecating finally - I have personally not found a use case for finally once this feature was added and suggest you avoid it. It's like goto or arguably continue, or even for loops as far as functional programming is concerned - newer features have made the use unnecessary.

like image 53
djechlin Avatar answered Oct 24 '22 10:10

djechlin