I found this strange behaviour not only when debugging but also during normal execution (at least I imagine so, based on how the application acted).
If I use the following code (in a function that returns int):
try {
return Integer.parseInt("3");
} catch (NumberFormatException ex) {
System.out.println(ex.getMessage());
return 0;
}
during debugging, after ‘return Integer.parseInt(“3”);’ the debugger jumps to ‘return 0;’. It seems to be entering the catch block, but skips the System.out line and doesn’t even show “ex” as an existing variable. Then the function returns 0.
But if I replace the above with the following:
int x;
try {
x = Integer.parseInt("3");
} catch (NumberFormatException ex) {
System.out.println(ex.getMessage());
x = 0;
}
return x;
then everything behaves as I’d expect it to: x gets the value of 3, and 3 is returned by the function.
For the good of me, I can’t figure out why this happens. Do you have any idea?
mah said:
Have you looked at the actual value being returned? Sometimes debuggers (due to optimizations applied) will jump to a return location which appears to be setting an inappropriate value, but in reality the return value has already been properly established.
And mah was right. I’m posting this here to make it clear it’s the answer.