处理Objects.requireNonNull()抛出的NullPointerException的最佳方法是什么?

hel*_*rew -5 java null android nullpointerexception

但是,这种方法似乎非常好,当将它与生产代码一起使用并将其用于可能为null 的对象时似乎很难处理.考虑我的例子:

public class ShowDialogTask extends AsyncTask<Void, Void, Void> {
    private WeakReference<Context> contextReference;

    public ShowDialogTask(Context context) {
        contextReference = new WeakReference<>(context);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        ...do a long running task...
        return null;
    }

    @Override
    protected void onPostExecute(Void void) {
        super.onPostExecute(void);
        Context ctx = Objects.requireNonNull(contextReference.get(), "Context became null");
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setTitle("Dialog title");
        builder.setCancelable(true);
        builder.create().show();
    }
Run Code Online (Sandbox Code Playgroud)

在onPostExecute()函数中,我使用Objects.requireNonNull方法设置局部变量对象ctx.我的问题是,我很难重现使contextReference.get()等于null,并且它肯定可能在生产中发生.

我想知道将此功能用于生产目的的最佳方法.

我的第一个想法是将代码包装在try-catch中,但是在任何地方都这样做似乎是糟糕的编程:

try {
    Context ctx = Objects.requireNonNull(contextReference.get(), "Context became null");
    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
    builder.setTitle("Dialog title");
    builder.setCancelable(true);
    builder.create().show();
} catch (Throwable t) {
    Log.d(TAG, t.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

And*_*ner 5

处理它的最佳方法是什么?不要把它扔在一开始.

捕获NullPointerException是你几乎不应该做的事情,除非你正在与一个写得不好的API进行交互.NullPointerException是一个未经检查的异常,这意味着它表示编程错误:最好修复编程错误.

使用条件检查事物是否为空,如果是,则执行不同的操作.

Context ctx = contextReference.get();
if (ctx != null) {
  // Use ctx.
} else {
  Log.d(TAG, "Context became null");
}
Run Code Online (Sandbox Code Playgroud)

在从更一般,醒目Throwable几乎从来没有做正确的事情,因为你可能会捕获和处理事情你不打算,导致吞咽你,你不知道,你必须处理的问题.