views:

42

answers:

2

I'm getting unexpected behavior in my Android 1.5 application under the Windows emulator and debugging with Eclipse. Here's a generalization of what the code is doing:

if (someCondition) {
    System.out.println("got here");
    return "a";
}

if (someOtherCondition)
    return "b"

return "c";

If I step through this code with the debugger, if someCondition is true it outputs "got here" but then jumps to the final return statement as if it's going to execute that line. From what I can tell, it is returning "a" but it's confusing because it seems like it is going to return "c."

If someCondition is false, and someOtherCondition is true, the debugger steps to the return "b" line - it doesn't jump to the final return statement and then leaves the method as expected.

As I mentioned, it seems like it is always returning the expected behavior but the fact that the debugger jumps to the wrong line had me chasing phantom bugs. A full rebuild, restarting Eclipse and restarting Windows each didn't address the problem - it's fully re-createable.

Any ideas?

A: 

just making sure: the actual code as a semicolon after return "b" -right? Missing semicolons always cause strangeness.

Aviendha
+1  A: 

Remember that your program that you execute and debug isn't written Java code - it's bytecode that was compiled from the Java code.

If you step through optimized C++ code, you can expect the cursor to jump around all across your code like stupid, depending on how much the scheduler was able to rearrange stuff.

Java is a lot more straightforward, but I would imagine that return instructions still get optimized out a bit, i.e. the clean-up part of the function is shared, so the return always gets you there.

Don't rely too much on the precise position of the cursor - instead, use debug output (which is also faster in practice).

EboMike
That seems like a reasonable explanation but on the other hand, I've been debugging Java for years and I've never seen this before. I'm willing to accept that the Android compiler might be doing more advanced things but it still feels weird to see this behavior in this one method and no where else in my code (yet). Thanks!
Thaliant
This answer is correct. You can see a very similar example called out in the Dalvik documentation at http://android.git.kernel.org/?p=platform/dalvik.git;a=blob_plain;f=docs/debugger.html;hb=HEAD (scroll down to "Known Issues and Limitations").
fadden