断言 VS 运行时异常 [英] Assertion VS Runtime exception

查看:47
本文介绍了断言 VS 运行时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing API, so my API will be used from external modules. And here is a one of methods where I can't figure out what to use assertion or 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);
}

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

If I use runtime exception, I think that it may harm the execution of the application which is using this API. If I use assertion then it will harm my API, if the assertion flag is disabled.

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

Also tried to read similar post When to use an assertion and when to use an exception. But it is bit confusing to detect which case is mine.

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

推荐答案

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

Assertions are usually a development technique that can be switched off in production. That's true in Java, Eiffel, C++, and every language that I know that uses them.

我个人更喜欢运行时异常来强制执行契约.你无法关闭它们.

Personally I prefer runtime exceptions to enforce the contract. You can't turn those off.

这篇关于断言 VS 运行时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆