В C# будет Наконец блок выполняться в попытке, выгоде, наконец если необработанное исключение будет брошено? [дубликат]

Не уверен, что вы действительно хотите достичь, но в вашей последней строке это то, что вы на самом деле делаете:

> df$c4[i = c(df$c2=="gg", df$c2=="ii", df$c2=="jj")]
[1] "qq" NA   NA  
> i = c(df$c2=="gg", df$c2=="ii", df$c2=="jj")
> i
 [1] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
[10] FALSE FALSE FALSE FALSE FALSE  TRUE
> df$c2
[1] "ff" "gg" "hh" "ii" "jj"

Вы передаете логический вектор длины 15 длине 5 символьный вектор, который не имеет особого смысла.

7
задан Community 23 May 2017 в 11:48
поделиться

10 ответов

finally is executed most of the time. It's almost all cases. For instance, if an async exception (like StackOverflowException, OutOfMemoryException, ThreadAbortException) is thrown on the thread, finally execution is not guaranteed. This is why constrained execution regions exist for writing highly reliable code.

For interview purposes, I expect the answer to this question to be false (I won't guarantee anything! The interviewer might not know this herself!).

28
ответ дан 6 December 2019 в 04:51
поделиться

Generally the finally block is guaranteed to execute.

However, a few cases forces the CLR to shutdown in case of an error. In those cases, the finally block is not run.

One such example is in the presence of a StackOverflow exception.

E.g. in the code below the finally block is not executed.

static void Main(string[] args) {
   try {
      Foo(1);
   } catch {
      Console.WriteLine("catch");
   } finally {
      Console.WriteLine("finally");
   }
}

public static int Foo(int i) {
   return Foo(i + 1);
}

The other case I am aware of is if a finalizer throws an exception. In that case the process is terminated immediately as well, and thus the guarantee doesn't apply.

The code below illustrates the problem

static void Main(string[] args) {
   try {
      DisposableType d = new DisposableType();
      d.Dispose();
      d = null;
      GC.Collect();
      GC.WaitForPendingFinalizers();
   } catch {
      Console.WriteLine("catch");
   } finally {
      Console.WriteLine("finally");
   }
}

public class DisposableType : IDisposable {
   public void Dispose() {
   }

   ~DisposableType() {
      throw new NotImplementedException();
   }
}

In both cases the process terminates before both catch and finally.

I'll admit that the examples are very contrived, but they are just made to illustrate the point.

Fortunately neither happens very often.

8
ответ дан 6 December 2019 в 04:51
поделиться

Не совсем верно, что finally всегда будет выполняться. См. этот ответ от Haacked :

Две возможности:

  • StackOverflowException
  • ExecutingEngineException

Блок finally не будет выполнен когда есть StackOverflowException поскольку в стеке нет места для даже выполнить еще какой-нибудь код. Так и будет также не называться, когда есть ExecutingEngineException, то есть very rare.

However, these two exceptions are exception you cannot recover from, so basically your process will exit anyway.

As mentioned by Mehrdad, a reliable try/catch/finally will have to use Constrained Execution Regions (CER). An example is provided by MSDN:

[StructLayout(LayoutKind.Sequential)]
struct MyStruct
{
    public IntPtr m_outputHandle;
}

sealed class MySafeHandle : SafeHandle
{
    // Called by P/Invoke when returning SafeHandles
    public MySafeHandle()
        : base(IntPtr.Zero, true)
    {
    }

    public MySafeHandle AllocateHandle()
    {
        // Allocate SafeHandle first to avoid failure later.
        MySafeHandle sh = new MySafeHandle();

        RuntimeHelpers.PrepareConstrainedRegions();
        try { }
        finally
        {
            MyStruct myStruct = new MyStruct();
            NativeAllocateHandle(ref myStruct);
            sh.SetHandle(myStruct.m_outputHandle);
        }

        return sh;
    }
}
3
ответ дан 6 December 2019 в 04:51
поделиться

Yes, finally is always executed.

4
ответ дан 6 December 2019 в 04:51
поделиться

Straight from MSDN:

The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits.

Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.

http://msdn.microsoft.com/en-us/library/zwc8s4fz(VS.71,loband).aspx

7
ответ дан 6 December 2019 в 04:51
поделиться

'Finally' is executed regardless of whether an exception is thrown or not.

Its a good place to close any open connections. Successful or failed execution, you can still manage your connections or open files.

0
ответ дан 6 December 2019 в 04:51
поделиться

Generally the finally block is always executed regardless of whether an exception is thrown or not and whether any exception is handled or not.

There are a couple of exceptions (see other answers for more details).

1
ответ дан 6 December 2019 в 04:51
поделиться

Finally block is guaranteed to be executed in any case.

-1
ответ дан 6 December 2019 в 04:51
поделиться

Finally is always executed. I not depends on how the try block works. If u have to do some extra work for both try and cath, it is better to put in finally block. So you can gurantee that it is always executed.

-1
ответ дан 6 December 2019 в 04:51
поделиться

Finally will happen everytime for that try catch block

-1
ответ дан 6 December 2019 в 04:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: