文档

java_lang_NullPointerException

问题分析

试图对一个为null的对象执行成员函数、试图获取null对象的成员变量、试图获取null数组的长度、试图访问数组中某个空对象、抛出一个对象而实际未初始化为null时,此时会抛出NullPointerException异常。

解决方案

对可以预见为空的对象进行处理,对不可预知的对象判断是否是null,然后再访问内部成员变量或执行成员函数。

代码示例

示例1

Exceptionin thread "main" java.lang.NullPointerException

判断对象是否为null,不是null再执行对象成员函数。

publicString[] split(String content){
if(content!=null){
String[] result=content.split("\\s+");
return result;
}
returnnull;
}

示例2

java.lang.NullPointerException
 at android.webkit.WebViewClassic$WebViewInputConnection.setNewText(WebViewClassic.java:587)
 at android.webkit.WebViewClassic$WebViewInputConnection.setComposingText(WebViewClassic.java:327)
 at android.webkit.WebViewClassic$WebViewInputConnection.commitText(WebViewClassic.java:343)
 at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:279)
 at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
 at android.os.Handler.dispatchMessage(Handler.java:107)
 at android.os.Looper.loop(Looper.java:194)
 at android.app.ActivityThread.main(ActivityThread.java:5391)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:525)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
 at dalvik.system.NativeStart.main(Native Method)

在使用Google Play Services的google-play-services.jar时报错,建议设置全局Exception Handler。

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, final Throwable ex) {
                // Custom code here to handle the error.
            }
        });
    }
}

参考文献

  • 本页导读 (0)
文档反馈