user2121 user2121 - 29 days ago 9
Android Question

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

Answer Source

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