首页 > 解决方案 > return null 和 throw 异常有什么区别?

问题描述

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

这个方法有一个 IBinder 作为返回值,但它只是抛出一个异常,我的问题不是关于服务,我的问题是为什么这个方法没有显示编译器错误?

如果我们写return null(如果我们不想实现这个方法)或者我们写抛出异常有什么不同?

标签: javareturnthrow

解决方案


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


推荐阅读