Yes, the finally block is started after the function returns, but it does not matter. Remember that the return value is passed by value, so a new temporary variable is created to return it to the temporary structure, so the finally block does not affect the actual return value. If you want to support the desired behavior, you can use the out parameter, for example:
static void Main(string[] args) { string answer; Sample(out answer); Console.WriteLine(answer); } public static void Sample(out string answer) { try { answer = "abc"; return; } catch (Exception) { throw; } finally { answer = "def"; } }
Or you can simply move the return statement outside of the try block, for example:
static void Main(string[] args) { string answer = Sample(); Console.WriteLine(answer); } public static string Sample() { string returnValue; try { returnValue = "abc"; } catch (Exception) { throw; } finally { returnValue = "def"; } return returnValue; }
However, given that the finally block will always override the return value, this is a dubious design.
Wedge
source share