Catch block and type conversion in C++

C++Server Side ProgrammingProgramming

In this section, we will see how to use the catch block for exception handling and the type conversion in C++.

At first, let us see a code, and we will see what will be the output, and how they are generating.

Example

#include <iostream>
using namespace std;
int main() {
   try{
      throw 'a';
   }
   catch(int a) {
      cout << "Integer value is caught :" << a;
   }
   catch(...) {
      cout << "Entering into default catch block";
   }
}

Output

Entering into default catch block

So, what is the reason behind this. Why this kind of output is generating? As we can see the character ‘a’ is thrown, but the first catch block is for int. If we think that the ASCII of ‘a’ is an integer, so will be entering into the first block, but that kind of conversions are not applicable for the catch blocks.

Let us see another example. In this example we will see the conversion constructor is not called for the thrown objects.

Example

#include <iostream>
using namespace std;
class TestExcept1 {};
class TestExcept2 {
   public:
      TestExcept2 (const TestExcept1 &e ){ // Defining the Conversion constructor
         cout << "From the Conversion constructor";
      }
};
main() {
   try{
      TestExcept1 exp1;
      throw exp1;
   } catch(TestExcept2 e2) {
      cout << "Caught TestExcept2 " << endl;
   } catch(...) {
      cout << "Entering into default catch block " << endl;
   }
}

Output

Entering into default catch block

The derived type objects are not converted to the base type objects while the derived type objects are thrown.

raja
Published on 02-May-2019 08:41:14
Advertisements