Finally區塊不應該使用Return,以免產生混淆

  • 3255
  • 0

Finally區塊不應該使用Return,以免產生混淆

依據MSDN的說明,在Visual Studio 2010中,當Try或者Catch區塊中有第一個Return陳述式,而Finally區塊有第二個Return陳述式,雖然程式執行時,會先遇到第一個Return陳述式之後才會執行第二個Return陳述式,但是在執行第一個Return陳述式之前,會先執行第二個Return陳述式,導致傳回值得實際結果與預期結果出現落差。

但是在Visual Studio 2012中實際測試的結果,會出現編譯時期錯誤:Control cannot leave the body of a finally clause。

測試程式碼如下:


        {
            string str = string.Empty;
            str="Step A";
            ViewBag.Message = str;
            try
            {
                str = " B";
                ViewBag.Message += str;
                return View();
            }
            catch (Exception ex)
            {
                str = " C";
                ViewBag.Message += str;
            }
            finally
            {
                str = " D";
                ViewBag.Message += str;
                //return View();
            }
            str = " E";
            ViewBag.Message += str;

            return View();
        }


下圖是執行結果:
image

Note
To avoid a potentially confusing situation, do not use a return statement in a finally block. The code in a finally block is run after a return statement in a try or catch block is encountered, but before that return statement is executed. In this situation, a return statement in the finally block is executed before the initial return statement, resulting in a different return value.

資料來源:
[1]try...catch...finally Statement
http://msdn.microsoft.com/en-us/library/vstudio/k4hea629(v=vs.100).aspx