what is different between return null and throw exception?

Viewed 543
@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

This method has an IBinder as return value, but it just throws an exception, my question is not about services, my question is that why this method does not show a compiler error?

and what is different if we write return null( if we do not want to implement this method) or we write throw exception?

2 Answers

Normally, throwing an exception is superior because it is considerably more informative than returning null, and because calling code can’t just blithely ignore the returned value in a way that leads to a subsequent and uninformative NullPointerException.

However, the documentation for onBind explicitly says that it’s okay to return null. Since that’s how the API is designed, it makes more sense to return null in this particular case than to throw an exception.

In general, throwing an exception is better, because it prevents calling code from assuming it’s okay to continue as if the operation succeeded when it did not in fact succeed. But in this case, the method is actually supposed to return null when the operation is not supported (which in my opinion is not a good design decision).

return null returns a null value. throw new whatever exception you throw aborts the execution of the method and raises an exception of the specified type. Throwing an exception in this case does not show a compiler error because if that's the only thing you do, you're never going to return anything, which is also valid. For example, if the exception was thrown in a branch of an if/else, you'd need to either throw an exception or return a value in the other branch, or you'd get the compiler error telling you that you must return a value of type IBinder.

Related