Java 初学者:如何使用作为参数传递的错误长度向量
如果我有一个执行元素明智加法的函数。我应该如何处理不匹配的向量长度:使用断言、IllegalArgumentException、创建我自己的检查异常类还是什么?
请注意,该函数位于其他程序员将使用的库中,但如果向量与开发人员不匹配,则通知开发人员非常重要。
If I'm having a function that does element wise addition. How should I deal with unmatched vector lengths: use Assertions, IllegalArgumentException
, create my own Checked Exception class or what?
Note the function is in a library which is going to be used by other programmers, but it's very important that if vectors doesn't match developer be notified.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是我使用的经验法则。
如果这是您期望并从中恢复的内容,请使用 CHECKED 异常。
如果这可能是程序员错误并且预计不会发生,请使用运行时异常。
如果没有更多的用户输入,您就无法真正从中恢复,所以对我来说,这听起来确实像是一个
IllegalArgumentException
。Here's the rule of thumb I use.
If it's something you EXPECT and RECOVER FROM, use a CHECKED exception.
If it's something that is probably a PROGRAMMER ERROR and is not expected to ever happen, use a RUNTIME exception.
You can't really recover from this without more user input, so it sure sounds like an
IllegalArgumentException
to me.我会抛出一个 IllegalArgumentException。确保在 Javadocs 中对此进行记录。
ArithmeticException 是另一种可能性,但我认为 `IllegalArgumentException 更适合它。
使用
assert
检查通常是关闭的,并且必须显式启用,通常仅在测试应用程序时而不是在生产使用中启用。因此,这仅适合检查私有方法,该方法始终应该获得正确的参数(通过调用方法中的检查来确保)。I would throw an IllegalArgumentException. Make sure you document this in the Javadocs.
An
ArithmeticException
would be another possibility, but I think an `IllegalArgumentException fits it better.Checking with
assert
is normally switched off and has to be enabled explicitly, often only while testing the application, not in productive use. Thus this is only suitable for checking in private methods, which always should get correct parameters (ensured by checks in the calling methods).如果调用者能够从中恢复,则抛出一个已检查异常。如果调用者无法从中恢复,则抛出 Unchecked Exception(例如
IllegalArgumentException
)。断言实际上只对跟踪您/他们的代码中的错误有用,因此这可能不是解决您所讨论问题的正确方法。If it's a case that the caller will be able to recover from, then throw a Checked Exception. If it's a case that the caller won't be able to recover from, throw an Unchecked Exception (e.g.
IllegalArgumentException
). asserts will really only be useful for tracking down errors in yours/their code, so that's probably not the right way to solve what you're talking about.IllegalArgumentException
和IndexOutOfBoundsException
都是不错的选择。您应该记录这一点,并将长度包含在异常消息中。Both
IllegalArgumentException
andIndexOutOfBoundsException
are fine choices. You should document this, and include the lengths in the exception message.