Search code examples
javareturnthrow

what is different between return null and throw exception?


@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?


Solution

  • 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).