Both the result and the exception to the java method call

I have weird Java behavior. At first, I thought it was a debugger error, but I can see the effects of the same behavior in production code. In the attached screenshot, I am at a breakpoint in the catch block, but somehow the result of the method that caused the exception is also present ( n = 4 and buf 4 bytes are written). As far as I know, this should not happen. Can someone explain how this is possible and how to avoid this behavior? Full code can be found here . src field java.io.PipedInputStream from the standard library.

enter image description here

+4
source share
1 answer

There is no inconsistency in the code. Since n defined outside the try block, it is in scope during the execution of the except block.

In addition, you handle the interrupt and continue the loop without any additional errors. Thus, the flow of the program also continues.

If you want your code to be interrupted, you must throw an interrupt and force those who call your function to catch it. If you want the return value to mean an error, you need to encode it in your domain (for example, if n represents the number of non-zeros received, you can return a negative number if an exception occurs).

+1
source

All Articles