Re: how to exit gracefully
On Dec 16, 12:01 pm, Eric Sosman <esos...@ieee-dot-org.invalid> wrote:
On 12/16/2010 11:01 AM, mark jason wrote:
hi,
I have an application that expects a certain number of command line
arguments.I need to check the number of command line args and if
sufficient number of arguments are not provided ,would like to print
the error message and exit.I have heard that using
System.exit(somenumber) is frowned upon.Which is the best practice?
regards
mark.
class MyApp{
....
public static void main(String[] args){
if (args.length< 4){
System.out.println("Usage: java MyApp =
fname sname
citycode statecode");
System.exit(1);
}
String firstname = args[0];
String surname = args[1];
String cityCode = args[2];
String stateCode = args[3];
new MyApp().process(firstname, surname, cityCode, st=
ateCode);
...
}
}
Since you're detecting the problem in main(), before you've
done anything like set up database connections or launch forty-two
worker threads, you could just return. My preference, though, would
be to throw an exception: It'll make more noise, and be more likely
to draw someone's attention.
I respectfully disagree. Exception messages and accompanying stack
traces are programmers' artifacts, not users'. A well-designed
application will translate internal exceptions into appropriate
external events such as a System.exit(nonZero) or domain-relevant
error message. Communication with the invoker should be in the domain
of the invoker, not the internal implementation domain of the service.
That rule of thumb allows 'System.exit()' for 'main()' applications
but deprecates it for container-based ones, as mentioned upthread, and
militates against the release of exceptions unprocessed to the outer
world.
--
Lew