How to catch exceptions in Visual C++ (815662)
The information in this article applies to:
- Microsoft Visual C++ 2005 Express Edition
- Microsoft Visual C++ .NET (2003)
- Microsoft Visual C++ .NET (2002)
- 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:
IN THIS TASKSUMMARYCatching 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
topRequirements
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
topHow 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.
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
using namespace System;
void _tmain(void)
{
Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
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:
- Click Project, and then click <ProjectName> Properties.
Note <ProjectName> is a placeholder for the name of the project. - Expand Configuration Properties, and then click General.
- 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.
For more information about the common language runtime support compiler option, visit the following Microsoft Web site:
These steps apply to the whole article. - Press F5. You receive a System.DivideByZeroException exception.
- 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:
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
using namespace System;
void _tmain(void)
{
try
{
Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
Console::WriteLine();
int i = 10;
int j = 0;
int k = i/j; //Error on this line.
}
catch(...)
{
Console::WriteLine("An error occurred.");
}
} - 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.
- 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:
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
using namespace System;
void _tmain(void)
{
try
{
Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
Console::WriteLine();
int i = 10;
int j = 0;
int k = i/j; //Error on this line.
}
catch(...)
{
Console::WriteLine("An error occurred.");
}
__finally //This section is performed regardless of the above processing.
{
Console::WriteLine();
Console::WriteLine("This statement is always printed");
}
} - Press CTRL+F5 to run the project.
- 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:
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
using namespace System;
using namespace System::Reflection;
void _tmain(void)
{
try
{
Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
Console::WriteLine();
int i = 10;
int j = 0;
int k = i/j; //Error on this line.
}
catch(Exception *e)
{
Console::WriteLine("An error occurred.");
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("This statement is always printed");
}
Console::ReadLine();
} - 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:
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
using namespace System;
using namespace System::IO;
using namespace System::Security;
void _tmain(void)
{
try
{
File::Create("c:\\temp\\testapp.txt"); //Can fail for a number of resons
}
// This error may occur if the temp folder does not exist.
catch(IOException *ioe)
{
Console::WriteLine("An IOException exception occurred!");
Console::WriteLine(ioe->ToString());
}
// You do not have the appropriate permission to take this action.
catch(SecurityException *se)
{
Console::WriteLine("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.
back to the
topREFERENCESFor more information about handling exceptions in Managed
Extensions for C++, see the following Microsoft Developer Network (MSDN) Web site: back to the top
Modification Type: | Major | Last Reviewed: | 1/5/2006 |
---|
Keywords: | kbHOWTOmaster kbhowto kbcode KB815662 kbAudDeveloper |
---|
|