J-CLOPS logoTWI-JUG logo

When something goes wrong

If during processing of the command line some problem occurs, then the system will throw an exception. Two different exception classes are used, depending on the type of error:

  • A CLParseException occurs when the user makes a mistake: an unknown option is used, an option argument of the wrong type is entered, etc. Catching this exception should provide the user with sufficient information on what she did wrong. For example:

    public static void main(String[] args) {
        HelloWorld myProgram = new HelloWorld();
        CLManager clm = new CLManager (myProgram);
        try {
           clm.parse(args);
            myProgram.run ();
        } catch (CLParseException ex) {
            System.out.println (ex);
        }
    }
                            

  • A CLDefinitionException is thrown when the error is due to some misconfiguration: the programmer has used an @Option and a @NotAnOption annotation for the same method, the same short option is configured for two different methods, etc. Usually there is no point in catching an exception of this type for it always indicates a programming error.

The CLManager class also provides a method getUsageMessage which provides a rudimentary 'usage message' that lists all available options. This message can be printed along with the exception:

    ...                    
    } catch (CLParseException ex) {
        System.out.println (ex);
        System.out.println (clm.getUsageMessage());
    }
}
        
To take full advantage of this feature, you should give a one line description of each option, as part of its @Option annotation. For example:
@Option(description="Message to be repeated")
public void setMessage (String message) {
    this.message = message;
}

@Option(shortName='t',longName="times-to-repeat",
        description="How many times to repeat")
public void setTimes(int times) {
    this.times = times;
}
        
Running HelloWorld now with argument -u will display the following message:
Unknown option: -u
Valid options are:
      --message          Message to be repeated
  -t, --times-to-repeat  How many times to repeat
        
(The first line arises from the exception, the others are the 'usage' message.)