An exception is not thrown using throw command

I am coding a method that return an instance of FragmentManager as shown in the code belwo. the prblem is, I want to throw an exception if the context passed to the method is null and then terminate the App.

what happens is, when I pass null to the method mentioned below, the App closes but the message in the NullPointerException which is :

getFragmentManagerInstance: Context reference is null

is not displayed

please let me know how to throw an exception and terminate the App correctly.

libs :

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;
    }
}

The message "getFragmentManagerInstance: Context reference is null" is being stored in e. You need to print it to make it display on the screen.

In the catch block, add a print statement before System.exit(1)

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

Just remove the try block. Simply typing

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

will do what you want, since NullPointerException is an unchecked exception.


is not displayed

Sure, that's because you're swallowing the exception:

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

The message is carried in e , and you're not using that in the catch block.


Note that it is almost never the right thing to do to catch a NullPointerException . In this case, you can simply print the message and terminate the app directly:

if (thing == null) {
  System.err.println("It's null!");
  System.exit(1);
}
链接地址: http://www.djcxy.com/p/13272.html

上一篇: 已弃用和旧版API之间的区别?

下一篇: 使用throw命令不会引发异常