Exception-Handling Sample

To get samples and instructions for installing them, see the following:

  • Click Samples on the Visual Studio Help menu.

    For more information, see Locating Sample Files.

  • The most recent versions and the complete list of samples are available on the Visual Studio 2008 Samples Web site.

  • You can also locate samples on your computer's hard disk. By default, samples and a Readme file are copied to a folder under \Program Files\Visual Studio 9\Samples\. For Visual Studio Express Editions, all samples are located on the Internet.

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.

Demonstrates

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.