rx-java2 - 为什么 Observable.subscribe() 会抛出 NullPointerException?
问题描述
我想知道如果我在 Observable 的 subscribe 方法中抛出一些异常会发生什么.. 例如:
Observable<SomeClass> observable = Observable.create(emitter -> {
throw new SomeException();
});
observable.subscribe(observer);
我在 rxjava 库中遇到了这段代码:
@SchedulerSupport(SchedulerSupport.NONE)
@Override
public final void subscribe(Observer<? super T> observer) {
ObjectHelper.requireNonNull(observer, "observer is null");
try {
observer = RxJavaPlugins.onSubscribe(this, observer);
ObjectHelper.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null Observer. Please change the handler provided to RxJavaPlugins.setOnObservableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins");
subscribeActual(observer);
} catch (NullPointerException e) { // NOPMD
throw e;
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
// can't call onError because no way to know if a Disposable has been set or not
// can't call onSubscribe because the call might have set a Subscription already
RxJavaPlugins.onError(e);
NullPointerException npe = new NullPointerException("Actually not, but can't throw other exceptions due to RS");
npe.initCause(e);
throw npe;
}
}
特别注意这段代码:
NullPointerException npe = new NullPointerException("Actually not, but can't throw other exceptions due to RS");
npe.initCause(e);
throw npe;
所以我的异常被包裹在一个 NullPointerException 中,而不是被直接抛出。我的问题是为什么以及这是什么意思:“实际上不是,但由于 RS 而不能抛出其他异常”..什么是 RS?
这对我来说似乎是非常狡猾的代码,文档中没有提到它
解决方案
推荐阅读
- python - 根据列表中的存在创建新的布尔熊猫列
- vba - 如何将vba代码分成多行?
- reactjs - 带有反应导航的父堆栈导航器上的自定义标题
- python - 如何在*抽象语法树之前编辑解析树?
- python - 在类中定义的全局变量
- python - 使用 tf.keras.models.save_model() 保存多输入 TF 2.x 子类模型时出现 TypeError
- python - 代码不同部分的不同 QFileSystemModel 行计数值
- javascript - 为什么我不能使用 getElementsByTagName() 获得多个输入值?
- python - ModuleNotFoundError: No module named 'psycopg2' (python3, mac, pip3 显示 psycopg2 安装成功)
- c# - 如何在使用 nlog 中记录无限字符消息