C# 使用没有“catch”块的“try-finally”块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9291437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:45:09  来源:igfitidea点击:

Use a 'try-finally' block without a 'catch' block

c#.netexceptionexception-handling

提问by mkus

Are there situations where it is appropriate to use a try-finallyblock without a catchblock?

在没有try-finally块的情况下使用块是否合适catch

采纳答案by Adam Houldsworth

You would use it to ensure some actions occur after the trycontent or on an exception, but when you don't wish to consume that exception.

您将使用它来确保在try内容之后或异常时发生某些操作,但是当您不希望使用该异常时。

Just to be clear, this doesn't hide exceptions. The finallyblock is run before the exception is propagated up the call stack.

需要明确的是,这并没有隐藏异常。该finally块在异常向上传播到调用堆栈之前运行。

You would also inadvertently use it when you use the usingkeyword, because this compiles into a try-finally(not an exact conversion, but for argument's sake it is close enough).

当您使用using关键字时,您也会不经意地使用它,因为这会编译为 a try-finally(不是精确转换,但出于参数的考虑,它已经足够接近了)。

try
{
    TrySomeCodeThatMightException();
}
finally
{
    CleanupEvenOnFailure();
}

Code running in finallyis not guaranteed to run, however the case where it isn't guaranteed is fairly edge - I can't even remember it. All I remember is, if you are in that case, chances are very good that not running the finallyisn't your biggest problem :-) so basically don't sweat it.

运行中的代码finally不能保证运行,但是不能保证它的情况相当边缘 - 我什至不记得它。我只记得,如果你在这种情况下,很有可能不运行finally不是你最大的问题:-) 所以基本上不要担心。

Update from Tobias:finallywill not run if the process is killed.

来自 Tobias 的更新:finally如果进程被终止,则不会运行。

Update from Paddy:Conditions when finally does not execute in a .net try..finally block

从 Paddy 更新:finally 不在 .net try..finally 块中执行时的条件

The most prevalent example you may see is disposing of a database connection or external resource even if the code fails:

您可能看到的最普遍的示例是即使代码失败也会处理数据库连接或外部资源:

using (var conn = new SqlConnection("")) // Ignore the fact we likely use ORM ;-)
{
    // Do stuff.
}

Compiles into somethinglike:

编译成类似的东西

SqlConnection conn;

try
{
    conn = new SqlConnection("");
    // Do stuff.
}
finally
{
    if (conn != null)
        conn.Dispose();
}

回答by IanNorton

You need a finally block, when no matter which (if any) exceptions are caught or even if none are caught you still want to execute some code before the block exits. For instance, you might want to close an open file.

您需要一个 finally 块,无论捕获到哪个(如果有)异常,或者即使没有捕获到,您仍然希望在块退出之前执行一些代码。例如,您可能想要关闭一个打开的文件。

See Also try-finally

另见try-finally

回答by Mitch Wheat

try/finally: when you do not want to handle any exceptions but want to ensure some action(s) occur whether or not an exception is thrown by called code.

try/finally:当您不想处理任何异常但想要确保发生某些操作时,无论被调用代码是否抛出异常。

回答by Amar Palsapure

usingis equivalent try-finally. You will only use try-finallywhen you want to do some clean up inside finallyand don't care about the exception.

using是等价的try-finally。只有try-finally当您想在内部进行一些清理finally并且不关心异常时才会使用。

The best approachwill be

最好的办法将是

try
{
   using(resource)
   {
       //Do something here
   }   
}catch(Exception)
{
     //Handle Error
}

Doing so even clean up called by usingfails, your code will not fail.

这样做即使清理调用using失败,您的代码也不会失败。

There are some condition when finallywill not get executed.

有一些条件何时finally不会被执行。

  • If there is any StackOverflowExceptionor ExecutingEngineException.
  • Process is killed from external source.
  • 如果有任何StackOverflowExceptionExecutingEngineException
  • 进程被外部源杀死。

Hope this answers your doubt.

希望这能解答你的疑惑。

回答by Jeb

If you have, for example an unmanaged resource you create and use in the try block, you can use the finally block to ensure you release that resource. The finally block will always be executed despite what happens (e.g. exceptions) in the try block.

例如,如果您拥有在 try 块中创建和使用的非托管资源,则可以使用 finally 块来确保释放该资源。尽管在 try 块中发生了什么(例如异常),finally 块将始终被执行。

E.g. the lock(x) statement is really:

例如 lock(x) 语句实际上是:

System.Threading.Monitor.Enter(x); 
try { ... } 
finally 
{ 
    System.Threading.Monitor.Exit(x); 
} 

The finally block will always get called to ensure the exclusive lock is released.

finally 块将始终被调用以确保排他锁被释放。

回答by Harsh

Have a look at the following link: https://softwareengineering.stackexchange.com/questions/131397/why-use-try-finally-without-a-catch-clause

看看以下链接:https: //softwareengineering.stackexchange.com/questions/131397/why-use-try-finally-without-a-catch-clause

It depends on the architecture of your application and the operation you are performing in the block.

这取决于您的应用程序的体系结构以及您在块中执行的操作。

回答by Neil G

I don't know anything about C#, but it seems that anything you could do with a try-finally, you could more elegantly do with a using statement. C++ doesn't even have a finally as a result of its RAII.

我对 C# 一无所知,但似乎可以用 try-finally 做的任何事情,都可以用using 语句更优雅地做。C++ 甚至没有 finally 作为其 RAII 的结果

回答by donstack

Good Explaination using code:

使用代码的好解释:

void MyMethod1()
{
    try
    {
        MyMethod2();
        MyMethod3();
    }
    catch(Exception e)
    {
        //do something with the exception
    }
}


void MyMethod2()
{
    try
    {
        //perform actions that need cleaning up
    }
    finally
    {
        //clean up
    }
}


void MyMethod3()
{
    //do something
}

If either MyMethod2 or MyMethod3 throws an exception, it will be caught by MyMethod1. However, the code in MyMethod2 needs to run clean up code, e.g. closing a database connection, before the exception is passed to MyMethod1.

如果 MyMethod2 或 MyMethod3 抛出异常,它将被 MyMethod1 捕获。但是,MyMethod2 中的代码需要在异常传递给 MyMethod1 之前运行清理代码,例如关闭数据库连接。

http://forums.asp.net/t/1092267.aspx?Try+without+Catch+but+with+finally+doesn+t+throw+error+Why+no+syntax+error+

http://forums.asp.net/t/1092267.aspx?Try+without+Catch+but+with+finally+doesn+t+throw+error+Why+no+syntax+error+

回答by Alex

Here's a use case that I always (uhm..) use:

这是我一直(嗯..)使用的用例:

int? x; //note the nullable type here!
try
{
    x = int.Parse(someString);
}
catch { } //don't care, let it just be null

回答by jazza1000

Here is a situation where you might want to use try finally: when you would normally use a using statement, but can't because you are calling a method by reflection.

在这种情况下,您可能希望使用 try finally:当您通常会使用 using 语句,但不能因为您通过反射调用方法而无法使用时。

This won't work

这行不通

using (objMsg  =  Activator.CreateInstance(TypeAssist.GetTypeFromTypeName("omApp.MessagingBO")))
{

}

instead use

而是使用

           object objMsg = null;
            try
            {
                objMsg
                   = Activator.CreateInstance(TypeAssist.GetTypeFromTypeName("myAssembly.objBO"));

                strResponse = (string)objMsg.GetType().InvokeMember("MyMethod", BindingFlags.Public
                        | BindingFlags.Instance | BindingFlags.InvokeMethod, null, objMsg,
                        new object[] { vxmlRequest.OuterXml });
            }               
            finally
            {
                if (objMsg!=null)
                    ((IDisposable)objMsg).Dispose();
            }