java 断言的使用,正确使用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.

解决方案

Not in this case.

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

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.

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");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值