国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

JDK1.4新特性:斷言

2019-11-17 06:01:33
字體:
來源:轉載
供稿:網友

  摘要

JDK1.4中引入的一個新特性之一就是斷言(assert),為程序的調試提供了強有力的支持,以下的文檔根據SUNTEC內容及相關內容組成。

  源代碼:

/**
* 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.    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 enab
le
at AssertExample.main(AssertExample.java:14)



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 白沙| 峨边| 章丘市| 腾冲县| 晋城| 滨州市| 新安县| 昌平区| 江达县| 尉犁县| 集安市| 醴陵市| 澄江县| 运城市| 嫩江县| 二手房| 三穗县| 蛟河市| 米林县| 绥化市| 昭通市| 江津市| 溧阳市| 岑溪市| 阿瓦提县| 平利县| 绥江县| 贡觉县| 马尔康县| 鲜城| 交城县| 两当县| 新宾| 剑阁县| 清丰县| 吴堡县| 黔江区| 寻甸| 龙井市| 南涧| 紫阳县|