码迷,mamicode.com
首页 > 编程语言 > 详细

java 断言

时间:2016-07-19 23:33:41      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

面试的时候遇到了一个什么时候才使用assert的问题----断言

当时懵了,不知道如何回答,结果面试官也说assert----断言在c语言中使用的可能比较多,java的话除非学的比较深,不然一

般不会了解到。委婉的给了基础不扎实的我一个台阶下吧。首先来看看java的api文档,来看看java.lang.Throwable类。

 

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are

instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by

the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a

catch clause.

 

意思是java中有且只有两类东西能够被java虚拟机throw和catch---error和exception。

exception我们就不说了大家都用的比较多,error有许多种,AssertionError就是Error的一个子类。AssertionError类一共

提供了七个构造函数确保断言的错误能够被激起。同时它也和Exception类一样继承了getCause,initCause方法用来抛别的

错误信息时保存原始的错误信息。有兴趣的可以了解下。

 

要想让断言起效用,即让断言语句在运行时确实检查,在运行含有assert的程序时,必须指定-ea选项
如:为了能够让下面的程序运行,我们执行下面代码:

public class TestAssert{
     public static void main(String[] args){
         String test;
         assert(name!=null):"变量test为空null";
         System.out.println(name);
     }
}


java -ea TestAssert,这时就会抛出一个assertionError:变量test为空null.

关闭断言使用的是 -da(disableAssertion).

由于断言在正式发布时是不起作用的,因此我们应该避免用其实现任何程序的实际行为,否则会出现测试时程序良好而发布后出现一些错误,如:

  public static void main(String[] args){
        TestPerson personObj = newTestPerson("a simple test");
        String personName = null;
        assert(personName=personObj.getName())!=null;
        System.out.println(personName.length());
    }

测试时没事,而发布后却出现空指针异常。

java 断言

标签:

原文地址:http://www.cnblogs.com/terminator-LLH/p/5686423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!