In Google's article on communicating with Fragments, the author gives the following example of checking to determine if a fragment's calling activity implements a required interface:
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
Normally, I prefer explicit checks to try/catch blocks. I this case, I would think the following example would be preferable:
if (activity instanceof OnHeadlineSelectedListener) {
mCallback = (OnHeadlineSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
Is there a reason to prefer one checking strategy over the other? Is there another strategy that should be used when defining interfaces to Fragments?