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)
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()fromquux, without touchingfooat all. What should now happen ifbartries to return tofoo, 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 mergefoofoofoointofoofoo, or change it to add afoofoofoofoo, without remembering to modifybar?An exception sounds exactly like the right tool for this job:
baz.bar()shouldn’t care that it has to go tofoo, it should know something exceptional has occurred, requiring it to abort what it’s doing, and thenfooshould 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.