tailieunhanh - Particular Statement Block
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 | 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 will always occur. After all it s right there in the code TextReader reader string line while line null line n 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 succeeds then it acquires a resource a file handle and you must ensure that you call 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 problem is as follows TextReader reader null try reader .
đang nạp các trang xem trước