Michael
Michael

Reputation: 6172

Java Invalid Command Line Arguments Exception

Is there an appropriate exception class for invalid command line arguments in the Java API or do I have to create my own? I've tried searching for one but can't find any in the API.

This is for an assignment so I cannot use third party libraries for command line parsing.

Upvotes: 13

Views: 22282

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347194

The best way to handle unknown command line parameters or combinations that don't make sense to the program is to display an error message and offer a usages output.

Personally, depending on the complexity of the command line, I will create a method called "usage" (usually static) that can have an optional error message passed to it.

While parsing the command line parameters passed into the program, I will call this method and either exit, via a flag or directly, or have usage method call exit for me.

But that's just me

Upvotes: 4

João Silva
João Silva

Reputation: 91299

Most of the times, when the received argument(s) are invalid, it's a common idiom to throw an IllegalArgumentException.

public class IllegalArgumentException extends RuntimeException

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Upvotes: 14

Makoto
Makoto

Reputation: 106400

The command line arguments come in as a String[]. If you're expecting the input to be in a certain form or a certain order, you can throw an Exception you create yourself to deal with it (although, throwing an exception would terminate the program; you'd need to handle it gracefully if that's required).

Upvotes: 0

Related Questions