Organize java code when using try catch finally blocks
•
Java
I am a novice in Java I have a question about how to organize java code when using try catch finally blocks Suppose I have to read some text files and do some calculations on the contents of the stored files What should my code do?
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 two are better coding practices? It should also be the last to block placement attempts to capture or it can be placed last
Solution
Use Java 7 and try with resources
try(Connection = pool.getConnection()) { // or any resource you open,like files // ... } // auto closes
This function is close to abandonment - once this function is added, I personally don't find a use case. I suggest you avoid using it As far as functional programming is concerned, it's like goto, or continuation, or even loop - update features make it unnecessary to use
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码