Microsoft KB Archive/815662

= How to catch exceptions in Visual C++ =

Article ID: 815662

Article Last Modified on 5/12/2007

-

APPLIES TO


 * Microsoft Visual C++ 2005 Express Edition
 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft Visual C++ .NET 2002 Standard Edition
 * Microsoft .NET Framework 1.0
 * Microsoft .NET Framework 1.1

-







For a Microsoft Visual C# .NET version of this article, see 308345.



For a Microsoft Visual Basic .NET version of this article, see 301283.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.IO
 * System.Security

IN THIS TASK

 * SUMMARY
 * Requirements
 * How to catch exceptions in Visual C++ .NET or in Visual C++ 2005
 * REFERENCES



SUMMARY
Catching and dealing with exceptions are standard programming tasks. This article describes how to use a try-catch-finally block to catch an exception. A try-catch-finally block is a wrapper that you put around any code where an exception might occur.

A try-catch-finally block is made up of the following sections:
 * Any code that may throw an exception is placed inside the try block.
 * If an exception is thrown, the catch block is entered, and the program can perform the appropriate operation to recover or to alert the user.
 * The code in the finally block is always executed and can perform cleanup after an exception occurs. The finally block is optional.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Windows XP Professional, Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, and Microsoft Windows Server 2003
 * Microsoft Visual C++ .NET or Microsoft Visual C++ 2005

back to the top

How to catch exceptions in Visual C++ .NET or in Visual C++ 2005
 Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project. In Visual Studio .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under Templates.

In Visual Studio .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.

In Visual C++ 2005, click Visual C++ under Project Types, and then click CLR Console Application under Templates. In the Name box, type Q815662, and then click OK.  Replace all the code in the Q815662.cpp code window with the following code. The code declares and initializes three variables. The initialization of k causes an error.
 * 1) include &quot;stdafx.h&quot;


 * 1) using 
 * 2) include <tchar.h>

using namespace System;

void _tmain(void) {   Console::WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;); Console::WriteLine; int i = 10; int j = 0; int k = i/j; //Error on this line. } Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps: <ol style="list-style-type: lower-alpha;"> Click Project, and then click  Properties.

Note  is a placeholder for the name of the project.</li> Expand Configuration Properties, and then click General.</li> Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.</li></ol>

For more information about the common language runtime support compiler option, visit the following Microsoft Web site:

/clr (Common Language Runtime Compilation)

http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

These steps apply to the whole article. </li> Press F5. You receive a System.DivideByZeroException exception.</li>  Wrap a try-catch statement around your code to capture the error. The following code catches all errors that are thrown in the code and displays a generic error message. Replace the code in the Q815662.cpp code window with the following code:
 * 1) include &quot;stdafx.h&quot;


 * 1) using <mscorlib.dll>
 * 2) include <tchar.h>

using namespace System;

void _tmain(void) {   try {       Console::WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;); Console::WriteLine; int i = 10; int j = 0; int k = i/j; //Error on this line. }   catch(...) {       Console::WriteLine(&quot;An error occurred.&quot;); } } </li> Press CTRL+F5 to run the application. Notice that the error message from the catch block is displayed instead of the system exception error message.</li>  If you must do cleanup or post-processing regardless of an error, use the __finally part of the try-catch-__finally statement. The code in the finally part of the statement is always executed, regardless of an exception. The following code displays the following message in the console, even if no error occurred:

This statement is always printed.

Replace the code in the Q815662.cpp code window with the following code:
 * 1) include &quot;stdafx.h&quot;


 * 1) using <mscorlib.dll>
 * 2) include <tchar.h>

using namespace System;

void _tmain(void) {   try {       Console::WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;); Console::WriteLine; int i = 10; int j = 0; int k = i/j; //Error on this line. }   catch(...) {       Console::WriteLine(&quot;An error occurred.&quot;); }   __finally //This section is performed regardless of the above processing. {       Console::WriteLine; Console::WriteLine(&quot;This statement is always printed&quot;); } } </li> Press CTRL+F5 to run the project.</li>  You can use the exception object with the catch statement to retrieve details about the exception. An exception object has a number of properties that can help you to identify the source and has stack information about an exception. This information can be very useful to help track down the original cause of the exception, or can provide a better explanation of its source. The following sample catches an exception and gives a specific error message. Replace the code in the Q815662.cpp code window with the following code:
 * 1) include &quot;stdafx.h&quot;


 * 1) using <mscorlib.dll>
 * 2) include <tchar.h>

using namespace System; using namespace System::Reflection;

void _tmain(void) {   try {       Console::WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;); Console::WriteLine; int i = 10; int j = 0; int k = i/j; //Error on this line. }   catch(Exception *e) {       Console::WriteLine(&quot;An error occurred.&quot;); Console::WriteLine(e->Message); // Print the error message. Console::WriteLine(e->StackTrace); //String that contains the stack trace for this exception. }   __finally //This section is performed regardless of the above processing. {       Console::WriteLine; Console::WriteLine(&quot;This statement is always printed&quot;); }   Console::ReadLine; } </li>  Until this point, you have dealt with a non-specific exception. However, if you know in advance what kind of exception is going to occur, you can catch the anticipated exception and process it accordingly. Use the multiple catch blocks that are described in the following code to catch all other exceptions and deal with them:
 * 1) include &quot;stdafx.h&quot;


 * 1) using <mscorlib.dll>


 * 1) include <tchar.h>

using namespace System; using namespace System::IO; using namespace System::Security;

void _tmain(void) {   try {       File::Create(&quot;c:\\temp\\testapp.txt&quot;); //Can fail for a number of resons }   // This error may occur if the temp folder does not exist. catch(IOException *ioe) {       Console::WriteLine(&quot;An IOException exception occurred!&quot;); Console::WriteLine(ioe->ToString); }   // You do not have the appropriate permission to take this action. catch(SecurityException *se) {       Console::WriteLine(&quot;An SecurityException exception occur    }    // Catch all exceptions    catch(Exception *e)    {        Console::WriteLine(e->ToString);    } }  Because computer configurations may be different, the sample in this step may or may not throw an exception. If you want to force an IO exception, change the file path to a folder that does not exist on your computer. </li></ol>

back to the top

Additional query words: exception try catch finally error

<div class="references_section">