LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 3062|回复: 3

避免NullPointerException异常的几种常用方法

[复制链接]
发表于 2004-5-24 13:44:53 | 显示全部楼层 |阅读模式
在写JAVA程序的时候,特别是jsp/servlet之类的东西,经常会有这样一种情况:当然你辛辛苦苦地打下了千百行字母的时候,写完最后一个大括号;当你运行这个程序进行调试时,忽然出现NullPointerException的字样,你是不是很懊丧呢。在以前我肯定会随手拿起桌上的杯子砸了。
    经过了一年多的打字母经历,我渐渐的总结出了一些经验,关于NullPointerException这个恶棍。
    NullPointerException这个异常出现在处理对象时对象不存在但又没有捕捉到进行处理的时候,但是在JAVA里面它又是被大多断片的类所抛出,所以它经常会不经意的出现在你的面前。在api里的原文说明是这样的:Thrown when an application attempts to use null in a case where an object is required. These include:

    * Calling the instance method of a null object.
    * Accessing or modifying the field of a null object.
    * Taking the length of null as if it were an array.
    * Accessing or modifying the slots of null as if it were an array.
    * Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.
    据我自己的统计,在我的代码中,出现频率最多的类是String.class,因此我们就以String为例来看一下怎么避免在使用这个类的时候遇到NullPointerException。
    从JAVA的源代码来看,String这个类一共在两个地方就抛出了NullPointerException这个异常,一个是String的一个构造方法,一个是toLowerCase这个方法,所以在用到这两个方法的时候最好捕捉一下异常。
    还有经常遇到的是equals这个方法,equals出现NullPointerException异常是因为对象不存在造成的。如果是变量和常量的比较,比如[php]str.equals("this is a string.")[/php],如果str == null。那么就会出现NullPointerException,怎么解决呢,就是把常量和变量的位置互换,[php]"this is a string.".equals(str)[/php],这样就不会再见到NullPointerException了。
    在jsp中经常会有一些form来提交表单给服务器,但是有时候表单项并没有填,那么在jsp程序对传上来的数据进行处理时,就会有异常出现。这时就要在使用这些数据前进行一次判断,如:[php]request.getParameter("str")[/php],如果没有任何处理就直接使用的话就有可能出错,但是如果这样
[php]
String tmp = "";
if(request.getParameter("str") != null)
    tmp = request.getParameter("str");
[/php]
然后再对tmp进行操作就没有问题了。当然,几乎所有的NullPointerException问题差不多都可以用这个方法解决。
    还有在使用JDBC的时候,ResultSet这个对象使用的时候也会经常有NullPointerException异常,一般来说ResultSet出现这个问题主要是sql不对的原因。

暂时就想到这些,欢迎大家来补充、批评、指正。
发表于 2004-5-24 18:54:34 | 显示全部楼层
这办法可行,我也是这样处理的.
发表于 2004-5-24 18:59:42 | 显示全部楼层

回复: 避免NullPointerException异常的几种常用方法

最初由 iDay 发表

    在jsp中经常会有一些form来提交表单给服务器,但是有时候表单项并没有填,那么在jsp程序对传上来的数据进行处理时,就会有异常出现。这时就要在使用这些数据前进行一次判断,如:[php]request.getParameter("str")[/php],如果没有任何处理就直接使用的话就有可能出错,但是如果这样
[php]
String tmp = "";
if(request.getParameter("str") != null)
    tmp = request.getParameter("str");
[/php]




我喜欢这样:
String tmp = request.getParameter("str") == null?"defaultString":request.getParameter("str");
 楼主| 发表于 2004-5-24 19:04:20 | 显示全部楼层
呵呵,一样的,一般我也会这样用的
但是有时候会有equals("")的情况要加进去的
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表