java assert 的作用,java – “assert”关键字有什么作用?

private static int charAt(String s, int d) {

assert d >= 0 && d <= s.length();

if (d == s.length()) return -1;

return s.charAt(d);

}

解决方法:

如果使用-enableassertions(或简称-ea)启动程序,则使用此语句

assert cond;

相当于

if (!cond)

throw new AssertionError();

如果在没有此选项的情况下启动程序,则assert语句将不起作用.

例如,断言d> = 0&& d< = s.length();,如您的问题中所述,相当于

if (!(d >= 0 && d <= s.length()))

throw new AssertionError();

(如果你使用-enableassertions启动了.)

14.10. The assert Statement

An assertion is an assert statement containing a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates to false. If the assertion is disabled, execution of the assertion has no effect whatsoever.

使用-ea开关控制“启用或禁用”并且“报告错误”表示抛出AssertionError.

最后,一个鲜为人知的断言功能:

您可以附加:“错误消息”,如下所示:

assert d != null : "d is null";

指定抛出的AssertionError的错误消息应该是什么.

该帖子已被重写为第here条.

标签:assertion,java,assert

来源: https://codeday.me/bug/20190916/1806839.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值