Conditions when, finally, are not satisfied in the .net try..finally block

Basically, I heard that certain conditions will cause .net to skip the last block. Does anyone know what these conditions are?

+43
exception-handling
Sep 21 '08 at 18:18
source share
6 answers

Two possibilities:

The finally block will not be executed when there is a StackOverflowException , since there is no space on the stack to even execute any code. It will also not be called when an ExecutionEngineException exists that may occur when Environment.FailFast() called.

+44
Sep 21 '08 at 18:23
source share

If the CLR does not explode and does not go down with ExecutingEngineException (I saw several .net 1.1 days with the right amount of COM Interop :) .. I think that in the end it should always execute.

+14
Sep 21 '08 at 18:21
source share

You may get a situation where the code in the try block raises a SecurityException before entering the try block (instead, an exception is thrown when the contains method is called (see http://msdn.microsoft.com/en-us/library/fk6t46tz(VS.71 ) .aspx )), in this situation you don’t even enter the try block, so the code in the finally block is never called.

Other features include StackOverflowException and ExecutingEngineException.

+5
Sep 21 '08 at 18:28
source share

Finally block on background thread may not run. However, this depends on the completion of the main foreground thread , which completes the background thread operation before the background thread .

 class Program { static void Main(string[] args) { Program prgm = new Program(); Thread backgroundThread = new Thread(prgm.CheckBgThread); backgroundThread.IsBackground = true; backgroundThread.Start(); Console.WriteLine("Closing the program...."); } void CheckBgThread() { try { Console.WriteLine("Doing some work..."); Thread.Sleep(500); } finally { Console.WriteLine("This should be always executed"); } } } 
+3
Nov 21 '16 at 2:05
source share

There is also a Application.Exit method.

+1
Dec 20 '08 at 20:29
source share

No code that follows the finally block, or code in external areas, will be executed without first executing the finally block (an exception in the finally block can lead to its premature termination, in which case execution will jump out of the finalizer for external coverage). If the code before the finally block gets stuck in an infinite loop or method that never exits, or if the execution context is completely destroyed, the finally block will not be executed.

Note that you end up blocking, unlike the Finalize methods (or C # destructors), which you should not rely on properly.

0
Sep 21 2018-11-21T00:
source share



All Articles