首页 > 解决方案 > 为什么 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?

这对我来说似乎是非常狡猾的代码,文档中没有提到它

标签: rx-java2

解决方案


推荐阅读