xhtml
 

How to Exit After an Error

The example program stops after detecting an error by calling System.exit, which you can look up in the online documentation by choosing the java.lang package and then the System class and then the exit method.

There are other ways you might have thought of to stop the program once the error has been detected. Perhaps the most obvious would be to use an else clause:

...
   public static void main(String[] args)
   {
      Check program = new Check();
      if (args.length != 2)
      {
         System.err.println("Usage: java Check x y");
      }
      else
      {
         program.report(args[0], args[1]);
      }
   }
...

Another way would be to use a return statement, which we haven't covered yet, but which you may know about:

...
   public static void main(String[] args)
   {
      Check program = new Check();
      if (args.length != 2)
      {
         System.err.println("Usage: java Check x y");
         return;
      }
      program.report(args[0], args[1]);
   }
...

Although these work in almost exactly the same way as the original, there is one slight difference, again to do with command window features. This time it is to do with scripts. A script is a file of commands which are executed by the command line system as if you had typed them. On many platforms, there is some way of saying "run the program, then if it succeeds do this and if it fails do that". The exact way in which you express this in a script varies from platform to platform, but you always need a way of telling whether a program has succeeded or failed.

There is a general convention that a program must return an exit code. The exit code should be zero to indicate success, and non-zero to indicate failure. Platforms differ about what different non-zero codes mean, so programmers often just return 1 as a general indication of failure.

The original version of the Check.java program calls System.exit in order to return an explicit exit code of 1 to indicate failure. This is the only way to do that. The other two techniques shown above return the default 0 exit code, indicating success.

This isn't a very important point, but if there is the faintest chance that your program could be used in a command script, you should keep to this convention to avoid severely irritating the script's author.


Back