Exception handling in Managed C++






1.95/5 (9 votes)
Aug 2, 2003
3 min read

89431

1258
An exception is any error occurring in the program at execution time. Exception handling increases the program reliability.
Introduction
An exception is any error occurring in the program at execution time. Exception handling gives several advantages for programmers. Exception handling increases the program reliability. The Microsoft VC++.NET framework supports for both managed C++ and unmanaged C++ exception handling. The Unmanaged C++ supports the SHE (Structured Exception Handling) type and COM based exception handling (return S_OK
or E_NOINTERFACE
). The Managed C++ supports CLR (Common Language Runtime) exception handling, and handling programmatically by programmer. The Managed C++ exception class is derived from the Exception
base class.
Exception Class
When the exception raises, the Exception
class object will be created. All the exception classes are derived from Exception
base class. The Exception
class supports for both predefined exception classes and user defined exception classes. The .NET framework supports for two types of exception handling. The exception generated by program and exception generated by CLR (Common Language Runtime). The Exception
class has some useful properties. The Stack
property contains a stack trace. It will give the name of the application. The HyperLink
property contains URL to a help file. The GetType
method is used to find the type of an exception. The Message
member is used to display a small description about the exception type.
The SystemException
is derived from the Exception
base class. The Exception
class is derived from the Object
root class. The SystemException
generates all the run time errors in managed C++. The user defined exceptions are derived from ApplicationException
. Most of the exception types are IndexOutOfRangeException
, FileNotFoundException
, NullReferenceException
, ArgumentNullException
and etc.
Try/Catch Block
The Try
/Catch
block is the block used to find the error when it occurs. The usage of Try
block is as following:
// try block code
try{
//……………………………
//……………………………
// source code that may generate exception
}
When the exception occurs, the control goes to catch
block. The catch
block catches the exception by specified type of exception or general type exception. If the exception is not caught by the catch
block, it will be caught by the Common Language Runtime Compiler. The proper exception handling is to specify the correct exception class. If these are not existing, it will caught by the general block.
// try / catch block
try{
// declare and initialize the variable
int i=0;
//Occur divide by Zero Exception
I=120/I+456;
// the condition go to catch block
Consoloe::WriteLine("This line does not Display!");
}
catch(Exception *e)
{
Console::WriteLine ("Exception Type:\n {0}", e->GetType()->ToString());
Console::WriteLine ("Exception Des:\n {0}", e->Message);
Console::WriteLine ("Stack Trace out:\n{0}", e->StackTrace);
}
Hierarchy of Exceptions:
Exception
Exception
is the base class for all exceptions. It is derived fromObject
base class.SystemException
SystemException
is the base class for all run time errors. It is derived fromException
class. TheIndexOutOfRangeException
,NullReferanceException
,InvalidOperationException
, andArgumentException
are the derived classes fromSystemException
. TheNullReferanceException
occurs when a null object is referred. TheArgumentException
is the base class for all argument exceptions.ArgumentException
The
ArgumentNullException
andArgumentOutOfRangeException
are the derived classes of theArgumentException
. TheArgumentNullException
occurs when you pass a null argument. TheArgumentoutOfRangeException
thrown when verifying the number of arguments.ComException
The
ComException
is derived fromExternalException
. This exception encapsulates the COM based errors.SEHException
The
SEHException
is also derived fromExternalException
. It encapsulates the Win32 based errors.
The try
block can have more then one catch
block. An exception is caught using the specific catch
block.
try
{
// Execute some code that might throw an exception.
}
catch(IndexOutOfRangeException * e )
{
// Handle out-of-memory exception
}
catch(NullReferanceException * e )
{
// Handle null reference exception
}
catch( Exception* e )
{
// Handle general exceptions here.
}
The first block catches the IndexOutOfRangeException
. The second block catches the NullReferanceException
, and the final catch
block catches the general exceptions.
The following example demonstrates exception handling:
// Display the Exeception Details
void DisplayMessage(String *exType,String *exMessage,String *exStack)
{
Console::WriteLine ("Exception Type:\n {0}", exType);
Console::WriteLine ("Exception Des:\n {0}", exMessage);
Console::WriteLine ("Stack Trace out:\n{0}", exStack);
}
// Divide by Zero Exception
void DivideException()
{
int i = 0;
try{
i=300/i;
}
catch(Exception *e)
{
DisplayMessage(e->GetType()->ToString(),
e->Message,e->StackTrace);
}
}
//Null Object reference Exception
void NullException()
{
Object *obj = (Object *)0;
try
{
Console::WriteLine(obj->ToString());
}
catch(Exception *e)
{
DisplayMessage(e->GetType()->ToString(),
e->Message,e->StackTrace);
}
}
// File Notfound Exception
void FileException()
{
try
{
FileStream *fs = new FileStream("data.txt", FileMode::Open);
StreamReader *sr = new StreamReader(fs);
}
catch(FileNotFoundException *e)
{
DisplayMessage(e->GetType()->ToString(),
e->Message,e->StackTrace);
}
}
// User defined Exception
__gc class MyException:public ApplicationException
{
public:
MyException(String *msg):ApplicationException(msg)
{
Console::WriteLine(msg);
}
};
The DisplayMessage
method is used to display all the exception details. This exception example displays four options. Give the option to user to choose the exception type.
Conclusion
The programmers choose the best place for handling the exception. Exception handling is used within the try
/catch
block. When creating the user-defined exception handling, the name should not be a reserved exception name. The .NET framework gives common exception handling mechanism for all the .NET-enabled languages. The unmanaged code use the SHE also. We also mix the managed C++ and unmanaged C++ code.