javaandroidrx-javarx-android

doOnError does not catch the exception


I am just getting started with RxJava, but maybe something did not click yet.

1.

Integer[] items = {1, 2, 3, 0, 0, 4, 5, 6, 1};
Observable.from(items)
        .map(this::invert)
        .subscribe(i -> Log.d(LOG_TAG, "Inverted: " + i), t -> Log.d(LOG_TAG, "Error: " + t.getMessage()));

2.

Integer[] items = {1, 2, 3, 0, 0, 4, 5, 6, 1};
Observable.from(items)
        .map(this::invert)
        .doOnError(t -> Log.d(LOG_TAG, "Error: " + t.getMessage()))
        .doOnNext(i -> Log.d(LOG_TAG, "Inverted: " + i))
        .subscribe();

The invert function:

int invert(int i) {
    return 1 / i;
}

The first executes normally, and when the exception is thrown the onError is executed. But on the other hand, the second does not work, so the exception is thrown all the way up to the calling method.

What is the difference between the two blocks of code?


Solution

  • Keep in mind that .doOnError() catches the exception, does something with it and then re-throws it. If you want different behavior, use one of the .onError* methods.

    Now, the reason why the exception does not propagate to the caller in #1 but does in #2 is that you've provided an error handler in #1, but not in #2, in which case the default is to propagate the exception.