简体   繁体   English

返回和最后一个子句 - 不一致的行为

[英]Return and finally clause - inconsistent behaviour

I came across slightly odd (IMO) code whcih behaves inconsistantly. 我遇到了一些奇怪的(IMO)代码,它的行为不一致。

try
{
   if (helperMethod())
   {
       return 0;
   }

   return 0;
 }
 catch(Exception e)
 {
    // Log and throw
 }
 finally
 {
     // Do a lot of stuff after value has been returned
 }

This sits inside a method which gets called by a VBA through by passing COM object to my DLL. 这位于一个方法中,该方法由VBA通过将COM对象传递给我的DLL来调用。 When it just runs, I don't get exception in C#, but I get a VBA exception. 当它刚刚运行时,我在C#中没有异常,但是我得到了一个VBA异常。

When I run this in a debug than I don't get exception anywhere. 当我在调试中运行它时,我不会在任何地方获得异常。

My guess is that logic in a finally clause takes over a second to run, and at that time 0 has already been returned by main body of the method. 我的猜测是finally子句中的逻辑需要花费一秒钟才能运行,并且此时0已经被该方法的主体返回。

I can re-write this in few ways, but I don't knwo whether it's common to write code in such a way...? 我可以用几种方式重写它,但我不知道以这种方式编写代码是否很常见......?

Thank you 谢谢

EDIT: Could it be that the COM object gets released when I return 0? 编辑:当我返回0时,COM对象是否会被释放? In that case it's no longer available in a finally clause. 在那种情况下,它在finally子句中不再可用。

COMException can crash your .NET CLR engine so that engine does not get a chance to run the finally code. COMException可能会导致.NET CLR引擎崩溃,导致引擎无法运行finally代码。 In these cases you will see an entry in the EventLog. 在这些情况下,您将在EventLog中看到一个条目。

I have seen a lot of these with WMI. 我用WMI看过很多这些。 Evil, evil ... 邪恶,邪恶......

I think here you may be trying (no pun intended) to use the finally block in an odd way. 我想在这里你可能正在尝试(没有双关语)以奇怪的方式使用finally块。 The Framework documentation typifies finally as follows: 框架文档最后表示如下:

The finally block is useful for cleaning up any resources allocated in the try block. finally块对于清理try块中分配的任何资源非常有用。

You should do your work within your try block (or outside the try-catch-finally construct if it's just covering a potential exception condition and not the subsequent processing of returned data) and your finally block should only release any resources allocated in the try that need to be released regardless of an exception or normal termination. 您应该在try块中(或者在try-catch-finally构造之外,如果它只是覆盖潜在的异常条件而不是后续处理返回的数据)进行工作,并且您的finally块应该只释放在try中分配的任何资源无论异常或正常终止,都需要被释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM