无论finally块中的内容是什么,它总是被执行(几乎),那么将代码封闭到它或不封闭它之间有什么区别呢?


当前回答

无论是否存在异常,finally块中的代码都将被执行。当涉及到某些需要经常运行的内务功能(如关闭连接)时,这非常方便。

现在,我猜你的问题是你为什么要这样做:

try
{
    doSomething();
}
catch
{
    catchSomething();
}
finally
{
    alwaysDoThis();
}

什么时候你可以这样做:

try
{
    doSomething();
}
catch
{
    catchSomething();
}

alwaysDoThis();

答案是,catch语句中的代码很多时候要么会重新抛出异常,要么会跳出当前函数。对于后一种代码,如果catch语句内的代码发出返回或抛出新异常,则“alwaysDoThis();”调用将不会执行。

其他回答

最后,如:

try {
  // do something risky
} catch (Exception ex) {
  // handle an exception
} finally {
  // do any required cleanup
}

是try. catch块之后执行代码的保证机会,而不管try块是否抛出异常。

这使得它非常适合于释放资源、db连接、文件句柄等。

有时您不想处理异常(没有catch块),但希望执行一些清理代码。

例如:

try
{
    // exception (or not)
}
finally
{
    // clean up always
}

Finally块的控制流在Try块或Catch块之后。

[1. First Code]
[2. Try]
[3. Catch]
[4. Finally]
[5. After Code]

除了 1 > 2 > 3 > 4 > if 3有Return语句 1 > 2 > 3 >

没有例外 1 > 2 > 4 > 如果2有一个返回语句 1 > 2 >

假设您需要将光标设置回默认指针,而不是等待(沙漏)光标。如果在设置光标之前抛出异常,并且没有完全崩溃应用程序,则可能会留下一个令人困惑的光标。

最后,语句甚至可以在返回后执行。

private int myfun()
{
    int a = 100; //any number
    int b = 0;
    try
    {
        a = (5 / b);
        return a;
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        return a;
    }

 //   Response.Write("Statement after return before finally");  -->this will give error "Syntax error, 'try' expected"
    finally
    {
      Response.Write("Statement after return in finally"); // --> This will execute , even after having return code above
    } 

    Response.Write("Statement after return after finally");  // -->Unreachable code
}