Behaviour of return statement in catch and finally

后端 未结 8 753
情歌与酒
情歌与酒 2020-11-27 11:44

Please see the following code and explain the output behavior.

public class MyFinalTest {

    public int doMethod(){
        try{
            throw new Exce         


        
相关标签:
8条回答
  • 2020-11-27 12:18

    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
    0 讨论(0)
  • 2020-11-27 12:21

    finally block will always execute (only exception is it encounters System.exit() anywhere before it), so simply the 5 is replaced (overridden) by 10 before returning by finally block

    0 讨论(0)
  • 2020-11-27 12:24

    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.

    0 讨论(0)
  • 2020-11-27 12:24

    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.

    0 讨论(0)
  • 2020-11-27 12:26

    In a nut shell, we could say finally block dominates return statement, irrespective of, if return present in try or catch block.

    Always finally dominates in that use case.

    public static int m1() {
        try {
            return 100;
        } 
        catch(Exception e)
        {
            return 101;
        }
        finally {
            return 102;
        }
    }
    

    Output - 102

    0 讨论(0)
  • 2020-11-27 12:29

    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"

    0 讨论(0)
提交回复
热议问题