what is the point of a finally block

时间:2015-07-28 17:04:00

标签: c# try-finally

So I thought the purpose of a finally block was to make sure certain statements were executed whether or not an error is thrown, but upon further reading I discover that finally won't execute if an error is unhandled. So what is the point of the finally if it doesn't execute? Wouldn't it be more functional just to have a catch(exception e) that executes the statements and then rethrows the error, because then you would at least know that what had to be executed was executed?

This code is what is bothering me:

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 

        }

Main window will close itself if certain conditions are met throwing an error, and I want the close statement to run even if that happens. MW.Show() throws an InvalidOperationException that breaks the program instead of executing the finally statement.

public MainWindow()
    {
        dm = new DataMover();
        InitializeComponent();
        if (DataMover.store.flagp||!DataMover.store.areAdmin())
        {
            NewAdminScreen nas = new NewAdminScreen();
            nas.Show();
            Close();
        }
    }

1 个答案:

答案 0 :(得分:2)

https://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx explains it very well:

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.

So finally is used to executed code in the block that you always want to run, regardless if an exception is thrown in the try block.

相关问题