user2121 user2121 - 5 months ago 43
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.


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) {
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) {
        return null;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download