Exception-Handling Sample
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

Exception-Handling Sample 

Download sample

This solution demonstrates structured-exception handling using Try...Catch...Finally.

Security noteSecurity Note

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

  1. Click Download Sample.

    The File Download message box appears.

  2. Click Open, and on the left column of the zip folder window, click Extract all files.

    The Extraction Wizard opens.

  3. Click Next. You can change the directory that the files will be extracted to, and then click Next again.

  4. Make sure that the Show extracted files check box is selected, and click Finish.

  5. 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   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.

See Also

© 2015 Microsoft