是“assert false;”一个很好的做法 [英] Is "assert false;" a good practice?

查看:189
本文介绍了是“assert false;”一个很好的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在根据给定的条件编写从列表中返回对象的函数。它看起来像这样:

I am currently writing a function returning an object from a list according to a given criteria. It looks like this:

for (Object object : list) {
    if (condition(object)) {
        return object;
    }
}

此函数应始终从列表中返回一些内容,在没有找到匹配对象的情况下,这是一个坏的调用,一个严重的错误,程序应该停止。

This function should always return something from the list, and in the case no matching object was found, it was a bad call, a critical error, and the program should stop.

所以,当我使用断言启用时,我在循环后执行以下操作:

So, as I work with assertions enabled, I did the following just after the loop:

assert false; // Will always trigger in debug mode.
return null; // No matter anyway, an AssertionException has already been thrown.

但是我想知道我是否表现不错?

如果没有,什么我该怎么办?自己抛出一个例外?

But I wonder if I did well or not?
If not, what should I do instead? Throws an exception myself?

无论如何,有没有关于这种情况的规范?

In any case, is there any kind of norm about this situation?

推荐答案

我宁愿尝试在调用函数时检查函数的返回值。

I would rather try to check the return value of the function when calling it.

if (yourFunctionWithList(parameter) == null)
   //error handling, maybe throw new NPException or whatever. 
else
   //some object was returned

您也可以自己写异常类并以任何方式处理它。

You may also write your own Exception class and handle it in any way you want.

我个人不认为 assert false 是好习惯。

I personally do not think assert false is good practice.

编辑

如果是关于将被抛出的 AssertionException ,那么你也可以使用它像

If it is about the AssertionException that will be thrown, then you could also use it like

throw new AssertionError ("your error msg here");

所以你可以一样处理它

这篇关于是“assert false;”一个很好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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