温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JDK1.4特性assert的示例分析

发布时间:2021-12-17 13:44:31 来源:亿速云 阅读:133 作者:小新 栏目:编程语言

这篇文章主要介绍了JDK1.4特性assert的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

源代码:

/**  * Simple examples of the use of the new assertion feature in JDK1.4  *  * @author S.Ritter 16/7/2001  **/ public class AssertExample {  public static void main(String[] args) {  int x = 10;  if (args.length > 0) {  try {  x = Integer.parseInt(args[0]);  } catch (NumberFormatException nfe) {  /* Ignore */ }  }  System.out.println("Testing assertion that x == 10");  assert x == 10:"Our assertion failed";  System.out.println("Test passed");  }  }

由于引入了一个新的关键字,所以在编译的时候就需要增加额外的参数,要编译成功,必须使用JDK1.4的javac并加上参数´-source 1.4´,例如可以使用以下的命令编译上面的代码:

javac -source 1.4 AssertExample.java

以上程序运行使用断言功能也需要使用额外的参数(并且需要一个数字的命令行参数),例如:

java -ea AssertExample 1

程序的输出为:

Testing assertion that x == 10 Exception in thread "main" java.lang.AssertionError: Our assertion failed  at AssertExample.main(AssertExample.java:20)

由于输入的参数不等于10,因此断言功能使得程序运行时抛出断言错误,注意是错误,这意味着程序发生严重错误并且将强制退出。断言使用boolean值,如果其值不为true则抛出AssertionError并终止程序的运行。

由于程序员的问题,断言的使用可能会带来副作用,例如:

boolean isEnable=false;  //...  assert isEnable=true;


这个断言的副作用是因为它修改程序变量的值并且没有抛出错误,这样的错误如果不细心检查很难发现。但是同时我们可以根据以上的副作用得到一个有用的特性,根据它测试是否将断言打开了。

/**  * Simple examples test enable assertion feature in JDK1.4  *  * @author Cherami 25/4/2002  **/ public class AssertExample2 {  public static void main(String[] args) {  boolean assertEnable=false;  assert assertEnable=true;  if (assertEnable==false)  {  throw new RuntimeException("Assertions should be enable");  }  }  }

如果我们不使用-ea参数运行上面的程序,则控制台将输出:

Exception in thread "main"   java.lang.RuntimeException: Assertions should be enable at AssertExample.main(AssertExample.java:14)

感谢你能够认真阅读完这篇文章,希望小编分享的“JDK1.4特性assert的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI