Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't my "finally" run?

I assume I'm missing something really trivial here but for reason it's not obvious to me. I've always assumed that "finally" always executes, regardless of an exception or not.

Anyway, this code failed to run and I'm not sure why. It gets to i = i/j and throws an DivideByZero exception but I would've thought it would continue and execute the finally statement before stopping.

static void Main(string[] args)
{
    int i = 1;

    try
    {
        int j = 0;
        i = i / j;

        Console.WriteLine("can't get");
    }
    finally
    {
        Console.WriteLine("finally ran");
    }
}
like image 961
Diskdrive Avatar asked Dec 22 '22 06:12

Diskdrive


1 Answers

Take a look at this MSDN try-finally (C# Reference)

From above link:

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement.

like image 160
Mark Hall Avatar answered Mar 27 '23 14:03

Mark Hall