Behaviour of return statement in catch and finally

孤街醉人 提交于 2019-11-26 19:41:27

It is overridden by the one in finally, because finally is executed after everything else.

That's why, a rule of thumb - never return from finally. Eclipse, for example, shows a warnings for that snippet: "finally block does not complete normally"

Vladimir Ivanov

finally is always executed (the only exception is System.exit()). You can think of this behavior this way:

  1. An exception is thrown
  2. Exception is caught and return value is set to 5
  3. Finally block gets executed and return value is set to 10
  4. The function returns

This is an easy question if you remember the low level layout of the VM.

  1. The return value is put up the stack by the catch code.
  2. Afterwards, the finally code is executed and overwrites the value on the stack.
  3. Then, the method returns with the most up to date value (10) to be used by the caller.

If unsure about things like this, fall back to your understanding of the underlying system (ultimately going to assembler level).

(funny sidenote)

The finally block is always executed (if the matching try was executed) so before the method returns 5 as in the catch block, it executes the finally block and returns 10.

Finally block always get executed unless and until System.exit() statement is first in finally block.

So here in above example Exection is thrown by try statement and gets catch in catch block. There is return statement with value 5 so in stack call value 5 gets added later on finally block executed and latest return value gets added on top of the stack while returning value, stack return latest value as per stack behavior "LAST IN FIRST OUT" so It will return value as 10.

the finally section will execute always execute. e.g. if you have any thing to release, or log out sort of thing, if error occur then go to catch section else finally will execute.

Session session //  opened some session 
try 
{
 // some error 
}
catch { log.error }
finally 
{ session.logout();}

it should not used to return anything. you can use outside of.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!