Consider the following java code:
public void write(FrameConsumer fc) throws FFmpegFrameRecorder.Exception{
frameStream.forEach(n -> fc.consume(n));
}
In this case "frameStream" is a Stream of Objects that can be passed to the "consume" method, and fc is a class containing the "consume" method. Another important note is that the "consume" method throws a "FFmpegFrameRecorder.Exception", which I would like to pass on to whatever method calls "write" in the future.
However the above code does not compile, because: "Unhandled exception type FFmpegFrameRecorder.Exception Java(16777384)". Why is that?
Best regards, CCI
EDIT: Puting a try_catch block inside the lambda expression does not solve the problem either, hence:
public void write(FrameConsumer fc) throws FFmpegFrameRecorder.Exception{
frameStream.forEach(n -> {
try {
fc.consume(n);
} catch (FFmpegFrameRecorder.Exception e) {
throw e; //**this part does not compile**
}
});
}
(As provided by @Soumya Manna) does not compile either. The compiler still wants for the program to handle the "FFmpegFrameRecorder.Exception e" as it is thrown.
The reason the lambda can't throw a checked exception is that java.lang.Stream#forEach
's parameter (action
) is of type java.util.function.Consumer
, whose only non-default
method, accept
, does not declare any exceptions.
See also: https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html