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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With