class CLIExceptionCapturer implements CommandLine.IExecutionExceptionHandler, CommandLine.IParameterExceptionHandler {

    @Override
    public int handleParseException(final CommandLine.ParameterException ex, final String[] args) {
        // This is an exception type from the library, handle as normal
        if (ex.getCause() == null) {
            final CommandLine cmd = ex.getCommandLine();
            final PrintWriter writer = cmd.getErr();

            writer.println(ex.getMessage());
            cmd.usage(writer);
        }

        // this exception was caused by us, throw it later
        this.thrown = (Exception) ex.getCause();
        return 0;
    }

}