使用 throw 命令不抛出异常

An exception is not thrown using throw command

我正在编写一种方法,return FragmentManager 的一个实例,如以下代码所示。 问题是,如果传递给该方法的上下文为空,我想抛出一个异常,然后终止应用程序。

发生的事情是,当我将 null 传递给下面提到的方法时,应用程序关闭但 NullPointerException 中的消息是:

getFragmentManagerInstance: Context reference is null

不显示

请告诉我如何抛出异常并正确终止应用程序。

:

public static FragmentManager getFragmentManagerInstance(Activity activity) throws Exception {

    try {
        if (activity != null) {
            return activity.getFragmentManager();
        } else {
            throw new NullPointerException("getFragmentManagerInstance: Context reference is null");
        }
    } catch (NullPointerException e) {
        System.exit(1);
        return null;
    }
}

is not displayed

当然,那是因为您吞下了异常:

} catch (NullPointerException e) {
    System.exit(1);
    return null;
}

消息在 e 中传送,您没有在 catch 块中使用它。


请注意,抓住 NullPointerException 几乎 从来都不是 正确的做法。在这种情况下,您可以简单地打印消息并直接终止应用程序:

if (thing == null) {
  System.err.println("It's null!");
  System.exit(1);
}

只需使用e.printStackTrace()

之前 System.exit(1)

它会按照您的意愿打印

该消息未显示,因为您尚未编写任何代码来打印它。如果要显示消息,请在退出前添加e.printStackTrace();

只需删除 try 块。只需输入

    if (activity != null) {
        return activity.getFragmentManager();
    } else {
        throw new NullPointerException("getFragmentManagerInstance: Context reference is null");
    }

会做你想做的,因为 NullPointerException 是一个未经检查的异常。

消息 "getFragmentManagerInstance: Context reference is null" 正在存储在 e 中。 您需要将其打印出来才能显示在屏幕上。

在catch块中,在System.exit(1)

之前添加打印语句
catch (NullPointerException e) {
        System.out.println(e);
        System.exit(1);
        return null;
}

为了打印一些信息,您需要将它们提供给输出流,例如 System.outSystem.err

默认情况下,如果您调用 ex.printstacktrace(),它将在 System.err 内打印异常。

您还可以使用 ex.printstacktrace(System.out) 选择发送信息的位置,例如文件、控制台或任何输出。

此外,您的应用程序将在 System.exit 之后立即停止,因此您的代码行需要在退出之前。

我很惊讶这还没有说明,将你的 catch 块更改为

} catch(NullPointerException e){
    System.err.print(e.getMessage());
    System.exit(1);
    return null;
}

如果您想向用户打印消息,请考虑使用 Toast 而不是异常消息。