java - What is the reason for this finally clause containing close() calls -


i'm studying online java course, introduction programming using java.

in chapter on i/o code below introduced following statement:

by way, @ end of program, you'll find our first useful example of clause in try statement. when computer executes try statement, commands in clause guaranteed executed, no matter what.

the program @ end of section 11.2.1 , simple program reads numbers in file , writes them in reverse order.

the relevant code in main method (data reader , result writer):

try {     // read numbers input file, adding them arraylist.             while ( data.eof() == false ) {  // read until end-of-file.         double inputnumber = data.getlndouble();         numbers.add( inputnumber );     }      // output numbers in reverse order.             (int = numbers.size()-1; >= 0; i--)         result.println(numbers.get(i));      system.out.println("done!");         } catch (ioexception e) {     // problem reading data input file.     system.out.println("input error: " + e.getmessage()); } {     // finish closing files, whatever else may have happened.     data.close();     result.close(); } 

so wondering why clause useful in case when there no other exit points try or catch clauses. couldn't close methods in body of main instead?

i thought maybe because there theoretically other runtimeexception crash program , leave reader & writers unclosed, wouldn't fact program had crashed close them anyway?

your idea correct: block close resources if unexpected exception ocurred.

you right irrelevant if such exception crashes complete application, looking @ code can't decide if case. there might other exception handlers, catching exception, , correct practice put closing logic in block.

note there still might bug hiding: if data.close() throws exception, result.close() never called.

depending on environment there various flavours on how fix bug.

  • in java 7 ff can use try-with-resources

  • if using spring, there might proper template similar jdbctemplate

  • if nothing of applies, yes you'll have try/finally inside finally. quit ugly. absolutely should @ least extract method suggested in comments.

  • conceptually cleaner rather wordy in java pre 8 implement loan pattern. if don't happen work scala/clojure/haskell developers might more confusing else.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -