简体   繁体   English

是否存在“命令行参数异常不足”?

[英]Is there “Not enough command line parameters exception”?

What exception should I throw if I wrote a program that expects more than 2 command line parameters and the user gave it an insufficient amount of arguments? 如果我编写的程序期望两个以上的命令行参数,而用户却给它提供了数量不足的参数,我应该抛出什么异常? I want to use the integrated exception handling. 我想使用集成的异常处理。

You shouldn't use an exception. 您不应使用异常。

Indeed, as answered by @Jennifer, ArgumentException is the standard exception for invalid arguments. 确实,正如@Jennifer回答的那样, ArgumentException是无效参数的标准异常。 But this isn't quite what it's normally used for, not what other programmers will expect reading your code, and not what users will expect running your program. 但这不是通常的用途,不是其他程序员期望阅读您的代码,也不是用户期望运行您的程序。

ArgumentException normally indicates a programmer error, where you pass in an invalid argument. ArgumentException通常指示程序员错误, 在其中传递了无效的参数。 It indicates a bug in your code: you should fix the code to either pass in a valid argument, or avoid the call if you know you don't have a valid argument. 它表明代码中存在错误:您应该修复代码以传递有效参数,或者如果知道没有有效参数,则避免调用。

In this case, that's not possible. 在这种情况下,这是不可能的。 Getting invalid arguments into Main is a user error, not a programmer error, and user errors should be handled differently. 将无效的参数放入Main是用户错误,而不是程序员错误,并且应对用户错误进行不同的处理。 Throwing an exception makes for a bad user experience: unhandled exceptions crash the program and get Windows to search online for a solution. 引发异常会带来糟糕的用户体验:未处理的异常会使程序崩溃,并使Windows在线搜索解决方案。 All that should be done here is to print an error message, and ideally exit with a non-zero status code. 这里要做的只是打印一条错误消息,理想情况下退出时会显示一个非零的状态代码。 There is no exception type that has that effect. 没有任何具有这种效果的异常类型。

ArgumentException is the standard for invalid arguments. ArgumentException是无效参数的标准。

The exception that is thrown when one of the arguments provided to a method is not valid. 提供给方法的参数之一无效时引发的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM