Re: Good practice or not to close the file before System.exit(1)?
On 4/22/2011 9:55 AM, Merciadri Luca wrote:
....
Okay. I might switch to exceptions for dealing with user input,
then. I was dubitative because of so many answers about this... For
example, at
<http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/8f3a236c4ff5a87e/4be4e8faf89e1b52?show_docid=4be4e8faf89e1b52>,
Mr. Green tells me that exit should be used for application data/user
errors. Surely exiting with System.exit won't give you any stack dump,
but my idea was the following: does the user really need a stack dump
when (s)he knows that he's given bad values to your program?
There are two separate questions: "What should the program as a whole
do?" and "What should an input validation method do?"
I think there is general agreement that main should not throw an
exception on user input error. Instead, the error should be reported,
for example by a message on standard output, and the program should
terminate with a non-zero status.
To produce that, you need to call System.exit() with the desired return
code.
Returning to the original question, if you have opened and written to an
output file, you need to close or flush it before the program terminates
to ensure output of any buffered data.
You should first use exceptions to get the information about the error
to an appropriate level in the program. If you find the error in main,
you will not need to do any exception work. If you find the error e.g.
in a conversion method, it should report it, probably through an
exception, to its caller. Generally, a conversion or validation method
should not be responsible for deciding to shut down the program.
The simplest way of doing clean-up is, as Stefan Ram recommends, to have
a single System.exit call at the end of main, and a returnCode variable.
The objective in the rest of the main program is to ensure that the
value of returnCode reflects what happened, including being zero if the
input was valid and everything worked.
Patricia