java断言机制

   

断言机制:允许java开发者在代码中加入一些检查语句,主要用于程序调试目的。

1.断言机制在用户定义的boolean表达式结果为false时抛出一个error对象,其类型为AssertionError;

2.当我们需要在约定的条件不成立时中断当前操作的话,可以使用断言;

3.作为Error的一种,断言失败也不需要捕获处理或者声明抛出,一旦出现了则终止程序、不必进行补救或恢复;

java运行时环境默认设置为关闭断言功能,所以在使用断言之前,需要在运行java程序时先开启断言功能。

开启:java -ea MyAppClass或者java -enableassertions MyAppClass

关闭:java -da MyAppClass或者java -disableassertions MyAppClass

用法1:assert <boolean表达式>

eg:

public class TestAssertion{

  public static void main(String [] args){

    new TestAssertion().process(-12);

  }

  public void process(int age){

    assert age>=0;

    System.out.println("您的年龄:"+age);

  }

}

执行java -ea TestAssertion运行结果:

Exception in thread "main" java.lang.AssertionError

   at TestAssertion.process(TestAssertion.java:7)

   at TestAssertion.main(TestAssertion.java:3)

执行java -da TestAssertion运行结果:

您的年龄:-12

用法2:assert <boolean表达式>:<表达式2>

eg:

public class TestAssertion{

  public static void main(String [] args){

    new TestAssertion().process(-12);

  }

  public void process(int age){

    assert age>=0:"年龄超出合理范围!";

    System.out.println("您的年龄:"+age);

  }

}

执行java -ea TestAssertion运行结果:

Exception in thread "main" java.lang.AssertionError:年龄超出合理范围!

   at TestAssertion.process(TestAssertion.java:7)

   at TestAssertion.main(TestAssertion.java:3)

执行java -da TestAssertion运行结果:

您的年龄:-12