Sí. Incluso si hubiera un Exception
dentro del bloque catch
, se ejecutará finally
.
Si está familiarizado con C++, solo piense en finally
como destructor
de object
. Cualquiera que sea el estado de una declaración dentro del objeto, ~Destructor
se ejecutará. Pero no puede poner return
dentro de finally
[aunque algunos compiladores lo permiten].
Vea el código a continuación: Vea cómo se ha cambiado la variable global y
. Vea también cómo Exception1
ha sido cubierto por 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();
}
}
}
salida:
>>>>>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
El primer caso no es impar. Ese es el punto de 'finalmente'. Ver http://stackoverflow.com/questions/65035/in-java-does-return-trump-finally. – kennytm
Verá, esperaría que 'return' fuera del alcance del bloque' try/catch/finally' y se aplique al método. No digo que esté mal que haga eso, pero ME ENCUENTRA desprevenido. Es algo a lo que nunca le había prestado atención. Creo que siempre llevé mis métodos hasta el final;) – lewiguez