冷面閻羅

          低調做人&&高調做事
          隨筆 - 208, 文章 - 3, 評論 - 593, 引用 - 0
          數據加載中……

          有關java的斷言

          源代碼:

          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;

            這個斷言的副作用是因為它修改程序變量的值并且沒有拋出錯誤,這樣的錯誤如果不細心檢查很難發現。但是同時我們可以根據以上的副作用得到一個有用的特性,根據它測試是否將斷言打開了。

          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)

          posted on 2007-04-05 08:58 冷面閻羅 閱讀(175) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 宜章县| 盐亭县| 新源县| 祁东县| 边坝县| 夏邑县| 同江市| 弋阳县| 民勤县| 三河市| 莆田市| 夏津县| 神木县| 新疆| 青阳县| 潼南县| 奉节县| 古蔺县| 麻江县| 西畴县| 大足县| 扬州市| 定远县| 武山县| 彰化市| 靖西县| 长乐市| 轮台县| 信阳市| 革吉县| 怀远县| 宜良县| 天津市| 福鼎市| 蕉岭县| 贵阳市| 开鲁县| 湖北省| 酒泉市| 祁连县| 城市|