views:

67

answers:

3

Using the return keyword in Java code will return execution to the last piece of calling code in the call stack. If object foo calls baz.bar(), the return keyword in the bar method will continue code execution in foo.

Let's say I have object foo that calls foofoo that calls foofoofoo in the above scenario, and foofoofoo calls baz.bar(). Is there anyway in Java to use the return keyword, or something else, so that the code in the bar method can return all the way back up to foo?

(WITHOUT THROWING AN EXCEPTION)

A: 

I'm not a huge Java guy, so I can't say for sure, but this does not sound like a safe thing to do and I would doubt that this would be supported in Java.

Now were this C/C++, you could make a dirty little hack that would overwrite the return address on the stack...

chi42
Were this C/C++ my life would be full of dirty little hacks, I'm sure. :-) However, you may have a point.
Finbarr
@Finbarr Whereas in Java we cleanly rewrite the bytecode on class load.
Tom Hawtin - tackline
@Tom point taken. Still not as hacky as C though, one hopes.
Finbarr
+2  A: 

No, this is not possible. You'll have to handle this yourself by code, one level at a time (an exception will do the same, it's just automated a bit more).

However, it's probably not a good idea to do this anyway. Suppose that you suddenly need to call baz.bar() from quux, without touching foo at all. What should now happen if bar tries to return to foo, which is not in the call stack? If you just want it to go up N levels, can you imagine the problems that might happen if you merge foofoofoo into foofoo, or change it to add a foofoofoofoo, without remembering to modify bar?

An exception sounds exactly like the right tool for this job: baz.bar() shouldn't care that it has to go to foo, it should know something exceptional has occurred, requiring it to abort what it's doing, and then foo should know that this exceptional situation can occur and handle it (even if it's just doing nothing is this case). If it's to avoid having to add a throws clause to everything, use an unchecked exception instead.

Michael Madsen
It's not to avoid a throws clause, it just seems alot to me like using Exceptions for control flow.
Finbarr
If you are able to check for this criteria before all of this, then you can do that instead - but sometimes, that just can't be determined in advance, and you'll have to throw the exception if it doesn't work out.
Michael Madsen
+1  A: 

Fortunately this is impossible in Java.

There are rare cases where similar things make sense, for example when you do context switching in an OS kernel.

But it is absolutely the wrong thing to do in application programs.

starblue
I didn't think it was possible to be honest, probably quite rightly so.
Finbarr