C++ Tutorial : Exceptions in C++/CLI

   Hi :) It’s Bright777 and today I want to show you a mechanism of catching exceptions in C++. First of all you need to know that is the exception how it can be caused. Exception is the action that can’t be completed due to the errors. For example, if you divide some number and zero, you will have an exception.    C++ can help you to catch exceptions. For this purposes C++ has special construction:
  1. try
  2. {
  3. //code, that can cause the exception
  4. }
  5. Catch()
  6. {
  7. //catching the exception
  8. }
   As you can see, block try includes the code, which can cause the exception. And block catch() catches the exception. In our example it catches all exception from the block try because catch has parameter(…) . Also you can catch exceptions of class, which you can do by yourself. Example Program    Now I will show you an example of program with exception catching mechanism. It is a Windows Forms Application. Program is very simple. In the edit control you need to type a number and press button to show it. If you type something else, it causes the exception. Here the code:
  1.         private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
  2.  
  3.                                
  4.                                 double a;
  5.  
  6.                                 try
  7.                                 {
  8.                                         a = Convert::ToDouble(textBox1->Text);
  9.                                         MessageBox::Show("Inserted number: "+a.ToString());
  10.                                 }
  11.  
  12.                                 catch(Exception^ ex)
  13.                                 {
  14.                                         MessageBox::Show( "Error!! Program has throwed an exception:\n\n "+ex->GetBaseException(),"Error",MessageBoxButtons::OK,MessageBoxIcon::Error);
  15.                                 }
  16.                          }
  17.         };
   So here you can see the source of the problem: if you assign String value to the variable of type double it causes the exception. So we put it in the block try and after that in the block catch we output the message about the exception (error). In that message we also add full information about the exception, like name, type, where it was caused. Output of the program
  1. Without exception: Good
  2. With exception: Bad
If you have some questions, you are welcome. If you liked program here is source code. See you.

Add new comment