Xem mẫu
- Using a finally Block
It is important to remember that when an exception is thrown, it changes the flow of
execution through the program. This means you can't guarantee that a statement will
always run when the previous statement finishes, because the previous statement might
throw an exception. Look at the following example. It's very easy to assume the call to
reader.Close will always occur. After all, it's right there in the code:
TextReader reader = src.OpenText();
string line;
while ((line = reader.ReadLine()) != null)
{
source.Text += line + "\n";
}
reader.Close();
Sometimes it's not an issue if one particular statement does not run, but on many
occassions it can be a big problem. If the statement releases a resource that was acquired
in a previous statement, then failing to execute this statement results in the resource being
retained. This example is just such a case: If the call to src.OpenText succeeds, then it
acquires a resource (a file handle) and you must ensure that you call reader.Close to
release the resource. If you don't, sooner or later you'll run out of file handles and be
unable to open more files (if you find file handles too trivial, think of database
connections instead).
The way to ensure a statement is always run, whether or not an exception has been
thrown, is to write that statement inside a finally block. A finally block occurs
immediately after a try block, or immediately after the last catch handler after a try block.
As long as the program enters the try block associated with a finally block, the finally
block will always be run, even if an exception occurs. If an exception is thrown and
caught locally, the exception handler executes first, followed by the finally block. If the
exception is not caught locally (the common language runtime has to search through the
list of calling methods to find a handler), the finally block runs first. In any case, the
finally block always executes.
The solution to the reader.Close problem is as follows:
TextReader reader = null;
try
{
reader = src.OpenText();
- string line;
while ((line = reader.ReadLine()) != null)
{
source.Text += line + "\n";
}
}
finally
{
if (reader != null)
{
reader.Close();
}
}
Even if an exception is thrown, the finally block ensures that the reader.Close statement
always executes. You'll see another way to solve this problem in Chapter 13, “Using
Garbage Collection and Resource Management.”
• If you want to continue to the next chapter
Keep Visual Studio 2005 running and turn to Chapter 7.
• If you want to exit Visual Studio 2005 now
On the File menu, click Exit. If you see a Save dialog box, click Yes.
nguon tai.lieu . vn