[英]Why is my null check unreachable?
In the following example i have an nullable property userId. 在以下示例中,我具有可为空的属性userId。 I would like throw an Exception if it null.
如果它为null,我想抛出一个异常。 Android studio is telling me the code block inside if(userId == null) is unreachable.
Android Studio告诉我if(userId == null)内的代码块不可访问。 Can anyone explain why this is unreachable?
谁能解释为什么这无法实现?
return Observable.create<Optional<UserEntity>> { it ->
val userId: String? = firebaseAuth.currentUser?.uid
if(userId == null){
it.onError(throw RuntimeException("Unauthorised"))
it.onComplete()
}else{
//Do something
}
}
Ok... I see... in fact it is the following line that contains the unreachable code: 好的...我知道了...实际上,以下行包含无法访问的代码:
it.onError(throw RuntimeException("Unauthorised"))
The reason: you throw your exception immediately and not when there occurs an error in processing. 原因:您立即引发异常,而不是在处理过程中发生错误时引发异常。 In fact the
onError
itself becomes unreachable. 实际上,
onError
本身无法访问。
onError
however, needs the exception to throw as passed argument, so what you rather want is something like: 但是
onError
需要将异常作为传递的参数抛出,所以您宁愿想要的是:
it.onError(RuntimException("Unauthorised"))
ie omit the throw
. 即忽略
throw
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.