|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
This solution demonstrates structured-exception handling using Try...Catch...Finally.
This sample code is provided to illustrate a concept and should not be used in applications or Web sites, as it may not illustrate the safest coding practices. Microsoft assumes no liability for incidental or consequential damages should the sample code be used for purposes other than as intended.
To open the sample file in Solution Explorer
Click Download Sample.
The File Download message box appears.
Click Open, and on the left column of the zip folder window, click Extract all files.
The Extraction Wizard opens.
Click Next. You can change the directory that the files will be extracted to, and then click Next again.
Make sure that the Show extracted files check box is selected, and click Finish.
Double-click the sample's .sln file.
The sample solution is displayed in Solution Explorer. You might get a security warning that says the solution location is not trusted. Click OK to continue.
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 Theclass 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 athat 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.