关于c#:finally块的重点是什么

what is the point of a finally block

本问题已经有最佳答案,请猛点这里访问。

因此,我认为finally块的目的是确保无论是否抛出错误,都执行了某些语句,但在进一步阅读后,我发现如果错误未经处理,finally将不会执行。那么,如果不执行finally有什么意义呢?仅仅让一个执行语句然后重新引发错误的catch(exception e)执行语句,难道不是更有用吗,因为这样至少您会知道必须执行的是什么?

这是困扰我的代码:

1
2
3
4
5
6
7
private void ASLogoff_Click(object sender, RoutedEventArgs e)
        {
            MainWindow MW = new MainWindow();
            try { MW.Show(); }// This throws an InvalidOperationException
            finally{ Close(); }//This code never executes

        }

如果满足某些条件并引发错误,则主窗口将自动关闭,即使发生这种情况,我也希望close语句运行。show()抛出一个invalidOperationException,它将中断程序而不是执行finally语句。

1
2
3
4
5
6
7
8
9
10
11
public MainWindow()
    {
        dm = new DataMover();
        InitializeComponent();
        if (DataMover.store.flagp||!DataMover.store.areAdmin())
        {
            NewAdminScreen nas = new NewAdminScreen();
            nas.Show();
            Close();
        }
    }


msdn.microsoft.com HTTPS:/ / / /图书馆/销售额zwc8s4fz.aspx explains恩很好:P></

By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur as a result of normal execution, of execution of a break,
continue, goto, or return statement, or of propagation of an exception
out of the try statement.

我知道finallyis used to executed队列中块,你总是想跑,如果数据库是扔在regardless安茶试块。P></