c# - 解释 "finally"在 try-catch-finally block 中的使用

标签 c# .net try-catch-finally

我读到 finally 键使 try-catch block 最终工作,甚至函数是否抛出异常。但我想知道如果我不将代码放在 finally block (如下面的 Function_2)中会有什么不同,这是我用来编码的方式。谢谢!

void Function_1()
{
    try
    {
        throw new Exception();
    }
    catch
    {
    }
    finally                                   //Have finally block
    {
        Other_Function();
    }
}

void Function_2()
{
    try
    {
        throw new Exception();
    }
    catch
    {
    }

    Other_Function();                        //Don't have finally block
}

最佳答案

if I dont put a code inside a finally block (like Function_2 below)

如果你不把代码放在 finally 中,除非你不会得到异常,否则代码块将被执行。

但是如果您在该代码块(未保留在 finally 中)将不会执行之前遇到异常,因为控件本身会从那里返回。

但是如果你把你的代码放在 finally 中,不管情况如何,它都会被执行。

示例:1 没有 finally block

 try
    {
    //throw exption
    }
    catch
    {
    //return from here
    }

    //below statement won't get executed
    Other_Function(); 

Example:2 with finally block

  try
    {
    //throw exption
    }
    catch
    {
    //return from here if finally block is not available 
    //if available execute finally block and return
    }
    finally
    {
    //below statement surly gets executed
    Other_Function(); 
    }

关于c# - 解释 "finally"在 try-catch-finally block 中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297516/

相关文章:

c# - 弱引用已死

c# - 使用在 install shield 中创建的安装程序添加 msi 文件

.net - 使嵌套 for 循环算法 - 动态

java - 我们可以在finally block 中使用 "return"吗

c# - 在 Dynamics CRM 2011 中发送多部分电子邮件(html+纯文本)?

c# - 将文件写入连接到 Windows PC 的 PNP 设备

asp.net - 从 ASP.NET 网站编译代码

.net - 对象上下文.翻译: avoiding column-mapping mistakes

java - 我不会在finally block 中使用try-catch 语句。 (java)

c# - 帮助处理finally block 中的异常