Why does stream api is not designed for Exception handling?

前端 未结 1 857
南方客
南方客 2021-02-06 18:50

Fixtures

BiConsumer> NOTHING = (ex, unused) ->{/**/};

When I try to fix the bug that is rep

1条回答
  •  隐瞒了意图╮
    2021-02-06 19:23

    I wouldn’t call this a bug—not even an unexpected behavior, given the fact that I warned about such scenarios in this comment on the linked question a month ago:

    Keep in mind that you don’t know whether the source iterator actually advanced its internal state or not when an exception has been thrown, so assuming that there is a next element can bring you into an infinite loop, repeating the failed operation over and over again.

    Of course, for the Stream.of(singleElement) case that scenario is easy to avoid and changing the order of the two statements, action.accept(first); and count = -1;, would make the code more robust, still, being able to recover from an exception is not a guaranteed feature at all and there are other stream sources for which such recovery couldn’t get implemented that easily.

    E.g., the streams returned by BufferedReader.lines(), resp. Files.lines() can’t force their underlying reader to advance one line if an IOException occurs.

    Generally, this attempt to recover from an exception makes the premature assumption that an exception thrown by the source always indicates a problem with a particular element rather than a problem with the source in general. This works with the contrived example where you know that the exception is associated with a particular element because you provoked it. But this is not how you can deal with unexpected exceptions, which is what exceptions usually are, as when you expect a particular problem, like string elements not being in number format, you should handle them straight-forwardly, like filtering out the invalid strings before parsing.

    0 讨论(0)
提交回复
热议问题