Thursday, July 29, 2010

Exit code idiom in Java

I have been looking into employing C 'enum' like exit codes in Java. For example, if the application you are writing will be called by a script so it is handy for the script to know when there is an exit that is OK, and when it is a FAIL.

I looked to the web for inspiration, and couldn't find anything Java specific, so, I have arrived at the following:

class MyClass {
  private static enum EXIT {
        OK(0), BAD_COMMANDLINE(1), INPUT_ERROR(10);
      
        EXIT (int code) {
            this.code = code;
        }
        private int code;
        public int getCode() {
            return code;
        }
    }

   public static void main (String[] args) {
        if (args.length() < 1) {
            System.exit(EXIT.BAD_COMMANDLINE.getCode());
        }

        System.exit(EXIT.OK.getCode());
    }
}

No comments: