调试程序里的NullPointerException

来源:互联网 发布:linux apache ab下载 编辑:程序博客网 时间:2024/05/02 06:32
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
 XForum的编码规范规定:必须对输入的参数进行null验证用的是Validation里的一个方法,检查对象是否为null:
   publicstaticvoidvalidateNotNull(finalObjecttestObject)
   {
       //Ifobjectisnull,thenanexceptionisthrown
       if(testObject==null)
       {
           thrownewIllegalArgumentException("Objectcan'tbenull.");
       }
   }
   如果把它改造成下面的形式,会使输出更加明显:
   publicstaticvoidvalidateNotNull(StringobjectName,Objectobject){
       if(object==null){
           thrownewIllegalArgumentException(objectName+"can'tbenull!!!");
       }
   }


   比如在真正的程序里:
publicvoidcheckLogon(Stringusername,Stringpassword){
 Validation.validateNotNull("username",username);
 Validation.validateNotNull("password",password);
 //...
}

   以后,在程序运行的过程中,如果再出现username为null的时候程序就会输出:java.lang.IllegalArgumentException:usernamecan'tbenull!!!

   哈哈,再不用为找null犯愁了。养成好的习惯,预防错误的发生,可以节省将来的好多时间。

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击