Why won't my “finally” work?

I suppose that I am missing something really trivial, but in my mind this is not obvious to me. I always assumed that "finally" is always executed regardless of exception or not.

In any case, this code did not run, and I'm not sure why. It gets into i = i / j and throws a DivideByZero exception, but I would think that it would continue to work 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"); } } 
+4
source share
5 answers

Take a look at MSDN try-finally (link to C #)

Top link:

Usually, when an unhandled exception terminates the application, the finally block fails, it does not matter. However, if you have a finally block that must be executed even in this situation, one solution is to add a catch block to the try-finally statement.

+5
source

Works for me - at least a few. When I run it as a console application from the command line, “Test.exe stops working. The window looks for a solution” appears immediately, but if I click the “Cancel” button, I see that “I finally ran”. If I let the initial dialog complete and just quit using Debug or Close, then clicking the Close button will end the process immediately and when hit, Debug will explicitly display the debugger.

EDIT: Hall's response explains the behavior in more detail. I will leave this answer as it contains experimental results, but look at Mark's answer :)

+4
source

Marking the answer says what happens, but I thought I would say why:

I believe this should allow any external handlers to handle the exception, which must be handled before the finally block is executed. (For example, when a debugger is connected, it may try to break at the exception point, which allows you to continue working before the finally block starts working.)

If the finally block was executed in advance, you cannot handle the exception in the debugger.

+2
source

try the following:

 static void Main(string[] args) { int i = 1;  try { int j = 0; i = i / j; Console.WriteLine("can't get"); } catch(Exception ex){ Console.WriteLine(ex.Message); } finally { Console.WriteLine("finally ran"); } Console.WriteLine("Press enter to exit..."); Console.ReadLine(); } 

code>

0
source

I think you may need to catch to catch the exception before finally launched.

0
source

Source: https://habr.com/ru/post/1382017/


All Articles