Книга: C# 2008 Programmer

The finally Statement

The finally Statement

By now you know that you can use the try-сatch block to enclose potentially dangerous code. This is especially useful for operations such as file manipulation, user input, and so on. Consider the following example:

FileStream fs = null;
try {
 //---opens a file for reading---
 fs = File.Open(@"C:textfile.txt", FileMode.Open, FileAccess.Read);
 //---tries to write some text into the file---
 byte[] data = ASCIIEncoding.ASCII.GetBytes("some text");
 fs.Write(data, 0, data.Length);
 //---close the file---
 fs.Close();
} catch (Exception ex) {
 Console.WriteLine(ex.ToString());
}
//---an error will occur here---
fs = File.Open(@"C:textfile.txt", FileMode.Open, FileAccess.Read);

Suppose that you have a text file named textfile.txt located in C:. In this example program, you first try to open the file for reading. After that, you try to write some text into the file, which causes an exception because the file was opened only for reading. After the exception is caught, you proceed to open the file again. However, this fails because the file is still open (the fs.Close() statement within the try block is never executed because the line before it has caused an exception). In this case, you need to ensure that the file is always closed — with or without an exception. For this, you can use the finally statement.

The statement(s) enclosed within a finally block is always executed, regardless of whether an exception occurs. The following program shows how you can use the finally statement to ensure that the file is always closed properly:

FileStream fs = null;
try {
 //---opens a file for reading---
 fs = File.Open(@"C:textfile.txt", FileMode.Open, FileAccess.Read);
 //---tries to write some text into the file---
 byte[] data = ASCIIEncoding.ASCII.GetBytes("1234567890");
 fs.Write(data, 0, data.Length);
} catch (Exception ex) {
 Console.WriteLine(ex.ToString());
} finally {
 //---close the file stream object---
 if (fs != null) fs.Close();
}
//---this will now be OK---
fs = File.Open(@"C:textfile.txt", FileMode.Open, FileAccess.Read);

One important thing about exception handling is that the system uses a lot of resources to raise an exception; thus, you should always try to prevent the system from raising exceptions. Using the preceding example, instead of opening the file and then writing some text into it, it would be a good idea to first check whether the file is writable before proceeding to write into it. If the file is read-only, you simply inform the user that the file is read-only. That prevents an exception from being raised when you try to write into it.

The following shows how to prevent an exception from being raised:

FileStream fs = null;
try {
 //---opens a file for reading---
 fs = File.Open(@"C:textfile.txt", FileMode.Open, FileAccess.Read);
 //---checks to see if it is writeable---
 if (fs.CanWrite) {
  //---tries to write some text into the file---
  byte[] data = ASCIIEncoding.ASCII.GetBytes("1234567890");
  fs.Write(data, 0, data.Length);
 } else Console.WriteLine("File is read-only");
} catch (Exception ex) {
 Console.WriteLine(ex.ToString());
} finally {
 //---close the file stream object---
 if (fs != null) fs.Close();
}

Оглавление книги


Генерация: 1.068. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз