user2121 user2121 - 26 days ago 8
Android Question

Is there an alternative way for nested try and catch?

In the below posted code, I am tring to code a utility method and I want to check if an object is null or not and a string is null and not empty.
so, I coded the way shown below with throwing some exception, but I think the code could have been coded in a better way because the way I coded it has nested
try and catch blocks.and i do not think it is a good style

please guide me to better code the belwo method

code:

public static boolean isFragmentShowing(Activity activity, String tag) throws Exception {

try {
if (activity != null) {
FragmentManager fragmentManager = FragmentUtils.getFragmentManagerInstance(activity);

try {
if (tag != null && !tag.equals("")) {
Fragment fragment = fragmentManager.findFragmentByTag(tag);

return (fragment != null && fragment.isVisible())? true : false;

} else {
throw new NullPointerException("isFragmentShowing: fragment tag passed is null or empty");
}
} catch (NullPointerException e) {
Log.e(TAG, "Error: " + e.getMessage().toString());
System.exit(1);
return false;
}

} else {
throw new NullPointerException("isFragmentShowing: context reference is null");
}
} catch (NullPointerException e) {
Log.e(TAG, "Error: " + e.getMessage().toString());
System.exit(1);
return false;
}
}

Answer Source

There are two part of your application. One is request validation and another one is application logic. Separate request validation and application logic. It will be easier to read and maintains. Here is my try in bellow

public static boolean isFragmentShowing(Activity activity, String tag) throws Exception {

//validate request 
if(activity == null) {
    // throw exception or return value 
}   
if (tag == null && tag.equals("")){
    // throw exception or return value 
}
// rest of the part
FragmentManager fragmentManager = FragmentUtils.getFragmentManagerInstance(activity);
Fragment fragment = fragmentManager.findFragmentByTag(tag);
return (fragment != null && fragment.isVisible())? true : false;
}