Java's strange behavior while returning from finally block

后端 未结 6 2184
梦谈多话
梦谈多话 2021-01-02 03:26

Try this piece of code. Why does getValueB() return 1 instead of 2? After all, the increment() function is getting called twice.

    public class ReturningF         


        
6条回答
  •  半阙折子戏
    2021-01-02 03:56

    The purpose of the finally method is to ensure that ressources are closed in any case. Consider the example:

    public List getPersons() {
        Connection conn = openConnection();
        try {
            return selectPersons(conn);
        } finally {
            conn.close()
        }
    }
    

    The conn.close() statement is executed AFTER selectPersons(conn) is executed. Otherwise selectPersons(conn) would raise an connection closed error.

提交回复
热议问题