1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace LoesFinallyReturn
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             Console.WriteLine("return i=" + test());
  11.             Console.ReadKey();
  12.         }
  13.         static public int test()
  14.         {
  15.             int i = 1;
  16.             try
  17.             {
  18.                 throw new Exception("Test");
  19.             }
  20.             catch
  21.             {
  22.                 return i;   // i=1 wird zurückgegeben, aber vorher wird finally ausgeführt
  23.             }
  24.             finally
  25.             {
  26.                 i++;
  27.                 Console.WriteLine("finally i="+i);
  28.             }
  29.         }
  30.     }
  31. }


Ausgabe

finally i=2
return i=1

Die Ausgabe zeigt, dass zuerst der finally-Block ausgeführt, noch bevor die Methode mit return verlassen wird.



Last modified: Thursday, 19 September 2019, 11:24 AM