断言 VS 运行时异常

Ars*_*yan 5 java runtime-error

我正在编写 API,因此我的 API 将从外部模块中使用。这是我无法弄清楚使用断言或什么的方法之一java.lang.IllegalArgumentException

/**
 * Adds translation of information to underlying store for particular language
 * @param languageId The identifier of the language 
 * @param translation The translation provided for the specific language
 * @throws AssertionError if the provided language id is {@code null} or empty
 *         or provided translation is {@code null} or empty
 */
public final void addTranslation(String languageId, String translation){
    assert !(Strings.isNullOrEmpty(languageId));
    assert !(Strings.isNullOrEmpty(translation));

    translations.put(languageId, translation);
}
Run Code Online (Sandbox Code Playgroud)

如果我使用运行时异常,我认为它可能会损害使用此 API 的应用程序的执行。如果我使用断言,那么如果断言标志被禁用,它将损害我的 API。

还尝试阅读类似的帖子何时使用断言以及何时使用异常。但要检测哪个案例是我的有点令人困惑。

是否有严格定义的方法,在哪里使用断言以及在哪里使用运行时异常?

duf*_*ymo 4

断言通常是一种可以在生产中关闭的开发技术。在 Java、Eiffel、C++ 以及我所知道的所有使用它们的语言中都是如此。

就我个人而言,我更喜欢运行时异常来执行契约。你无法关闭它们。