This solution demonstrates structured-exception handling using Try...Catch...Finally.
To get samples and instructions for installing them
Do one or more of the following:
On the Help menu, click Samples.
The Readme displays information about samples.
Visit the Visual Studio 2008 Samples Web site. The most recent versions of samples are available there.
Locate samples on the computer on which Visual Studio is installed. By default, samples and a Readme file are installed in drive:\Program Files\Microsoft Visual Studio 9.0\Samples\lcid. For Express editions of Visual Studio, all samples are located online.
For more information, see Visual Studio Samples.
This sample code is intended to illustrate a concept, and it shows only the code that is relevant to that concept. It may not meet the security requirements for a specific environment, and it should not be used exactly as shown. We recommend that you add security and error-handling code to make your projects more secure and robust. Microsoft provides this sample code "AS IS" with no warranties.
To run this sample
Press F5 to start the application in Debug mode using the breakpoints. Press CTRL+F5 to run the program and ignore the breakpoints.
Five variations on opening a file are demonstrated in the code. There are five command buttons to test. Each one tries to open the file specified in the text box labeled Text File To Open. Each button, except the one labeled No Error Handling, uses various degrees of error handling using Try, Catch, and Finally blocks.
No error handling The FileStream class is used to open the file specified in the form. If the file does not exist, an exception is thrown. In release mode, program execution stops. In debug mode, the Exception Assistant is shown.
Basic error handling The call to open the file is wrapped in a Try...Catch...Finally Statement (Visual Basic) that catches all errors. The error message is displayed and program execution continues.
Detailed error handling Multiple Catch clauses are used to provide more detail about the error. By catching specific errors, the program can determine whether the file did not exist, the folder did not exist, or some other I/O error occurred.
Custom Message Using multiple Catch clauses and the stack trace, the program provides a detailed error message about the exception.
Try, Catch, Finally The Finally clause is used to close the file if it has been opened.