Да. Даже если в блоке catch
было Exception
, finally
будет выполнено.
Если вы знакомы с C ++, просто подумайте finally
как destructor
из object
. Каково бы ни было состояние оператора внутри объекта, ~Destructor
будет выполнено.
Но вы не можете поместить return
в finally
[хотя некоторые компиляторы допускают].
См. Код ниже: Посмотрите, как изменилась глобальная переменная y
.
Также посмотрите, как Exception1
был покрыт Exception2
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace finallyTest
{
class Program
{
static int y = 0;
static int testFinally()
{
int x = 0;
try
{
x = 1;
throw new Exception("Exception1");
x = 2;
return x;
}
catch (Exception e)
{
x = -1;
throw new Exception("Exception2", e);
}
finally
{
x = 3;
y = 1;
}
return x;
}
static void Main(string[] args)
{
try
{
Console.WriteLine(">>>>>" + testFinally());
}
catch (Exception e)
{ Console.WriteLine(">>>>>" + e.ToString()); }
Console.WriteLine(">>>>>" + y);
Console.ReadLine();
}
}
}
выход:
>>>>>System.Exception: Exception2 ---> System.Exception: Exception1
at finallyTest.Program.testFinally() in \Projects\finallyTest\finallyTest\Program.cs:line 17
--- End of inner exception stack trace ---
at finallyTest.Program.testFinally() in \Projects\finallyTest\finallyTest\Program.cs:line 24
at finallyTest.Program.Main(String[] args) in \Projects\finallyTest\finallyTest\Program.cs:line 38
>>>>>1