Click here to Skip to main content
15,881,812 members
Articles / Programming Languages / C++/CLI
Article

Exception handling in Managed C++

Rate me:
Please Sign up or sign in to vote.
1.95/5 (12 votes)
1 Aug 20033 min read 88.5K   1.2K   20   4
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:

MC++
// 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.

MC++
// 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 from Object base class.

  • SystemException

    SystemException is the base class for all run time errors. It is derived from Exception class. The IndexOutOfRangeException, NullReferanceException, InvalidOperationException, and ArgumentException are the derived classes from SystemException. The NullReferanceException occurs when a null object is referred. The ArgumentException is the base class for all argument exceptions.

  • ArgumentException

    The ArgumentNullException and ArgumentOutOfRangeException are the derived classes of the ArgumentException. The ArgumentNullException occurs when you pass a null argument. The ArgumentoutOfRangeException thrown when verifying the number of arguments.

  • ComException

    The ComException is derived from ExternalException. This exception encapsulates the COM based errors.

  • SEHException

    The SEHException is also derived from ExternalException. 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.

MC++
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:

MC++
// 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
India India
Selvam has worked on several technologies like Java, Python, Big data, VC++, MFC, Windows API and Weblogic server. He takes a lot of interest in reading technical articles and enjoys writing them too. He has been awarded as a Microsoft Community Star in 2004, MVP in 2005-06, SCJP 5.0 in 2009, Microsoft Community Contributor(MCC) 2011.

Big Data
o Google Professional Data Engineer 2021
o Confluent Certified Developer for Apache Kafka 2020
o Datastax Apache Cassandra 3.x Developer Associate Certification 2020
✓ Cloud
o Google Professional Cloud Architect 2021
o Microsoft Certified: Azure Solutions Architect Expert 2020
o AWS Certified Solutions Architect - Associate 2020
✓ Oracle Certified Master, Java EE 6 Enterprise Architect (OCMEA) 2018

Github : https://github.com/selvamselvam
Web site: http://www.careerdrill.com
Linkedin: https://www.linkedin.com/in/selvamselvam/

Comments and Discussions

 
QuestionException catch causing crash?? Pin
ChrisRibe5-Oct-06 11:44
ChrisRibe5-Oct-06 11:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.