Java 无效的命令行参数异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12208299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Invalid Command Line Arguments Exception
提问by Michael
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.
Java API 中是否有适用于无效命令行参数的异常类,还是我必须创建自己的异常类?我试过搜索一个,但在 API 中找不到任何一个。
This is for an assignment so I cannot use third party libraries for command line parsing.
这是一个作业,所以我不能使用第三方库进行命令行解析。
采纳答案by MadProgrammer
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.
就个人而言,根据命令行的复杂程度,我将创建一个名为“usage”(通常是静态的)的方法,该方法可以将可选的错误消息传递给它。
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.
在解析传递给程序的命令行参数时,我将调用此方法并通过标志或直接usage
退出,或者让方法调用退出。
But that's just me
但这只是我
回答by Jo?o Silva
Most of the times, when the received argument(s) are invalid, it's a common idiom to throw an IllegalArgumentException
.
大多数时候,当接收到的参数无效时,抛出IllegalArgumentException
.
public class IllegalArgumentExceptionextends RuntimeException
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
公共类IllegalArgumentException扩展了 RuntimeException
抛出以指示方法已传递非法或不适当的参数。
回答by Makoto
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).
命令行参数以String[]
. 如果您希望输入采用某种形式或某种顺序,您可以抛出一个您自己创建的异常来处理它(尽管抛出异常会终止程序;如果这是必需的)。