正确使用Java“断言”关键词 [英] Correct use Java "assert" keyword

查看:472
本文介绍了正确使用Java“断言”关键词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有理解用于什么是断言,尽管我已经阅读了很多例子,但他们并没有真正让我知道我应该使用它的原因是什么。

I have never understood what is assert used for, even though I have read plenty examples, they don't really let me know what or why should I use it for.

所以不要问一个例子,我会提供一个,如果这是断言

So Instead of asking an example, I'm gonna provide one and let me know if this is the proper usage of assert.

// The idea is that the `mode` variable should be 0 or 1, and no other number.
switch(mode) {
     case 0: 
          // do stuff
          break;
     case 1:
          // do other stuff
          break;

     default:
          // assert code?
}

如果这是正确的,请告知我在这种情况下如何使用它。如果这不是它应该如何使用,请提供一个例子。

If this is correct, please let me know how to use it in this case. If this is not how it is supposed to use, please provide an example.

推荐答案

不是这种情况。

如果您断言一个值,那么您正在做一个声明,在使用此值完成一些关键评估之前,它就是您声明的那个。您可以声明该值不为null,或者它小于2,或之前到达关键代码块。

If you're asserting a value, you're making a statement that, before some critical evaluation is done using this value, that it is what you assert it to be. You can assert that the value isn't null, or that it's less than 2, or something before you reach your critical code block.

assert (mode >= 0 && mode < 2);  // Ensures that `mode` is between 0 and 1.
// Switch statement to follow



<我不鼓励在这里使用它。您的代码读取不好,除非您使用 -ea 标志启用断言,否则您的断言将无效。

I would not encourage the use of that here. Your code would not read well, and unless you enable assertions with the -ea flag, your assertion would not work.

相反,你可以做的是抛出某种异常 - 如果它不是0或1,那么模式是一个无法处理的非法值,导致特殊/未定义的行为。抛出某种异常。

Instead, what you can do is throw an exception of some kind - if it's not 0 or 1, then the mode is an illegal value which cannot be processed, leading to exceptional/undefined behavior. Throw an exception of some kind.

switch(mode) {
    case 0: 
        // do stuff
        break;
    case 1:
        // do other stuff
        break;
    default:
      throw new IllegalArgumentException("Mode is illegal");
}

这篇关于正确使用Java“断言”关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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