Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Catch block and type conversion in C++

  • Difficulty Level : Medium
  • Last Updated : 12 Nov, 2021

Predict the output of following C++ program.

Hey! Looking for some great resources suitable for young ones? You've come to the right place. Check out our self-paced courses designed for students of grades I-XII

Start with topics like Python, HTML, ML, and learn to make some games and apps all with the help of our expertly designed content! So students worry no more, because GeeksforGeeks School is now here!

 

C++




#include <iostream>
using namespace std;
 
int main()
{
    try
    {
        throw 'x';
    }
    catch(int x)
    {
        cout << " Caught int " << x;
    }
    catch(...)
    {
        cout << "Default catch block";
    }
}

Output:



 Default catch block

In the above program, a character ‘x’ is thrown and there is a catch block to catch an int. One might think that the int catch block could be matched by considering ASCII value of ‘x’. But such conversions are not performed for catch blocks. Consider the following program as another example where conversion constructor is not called for thrown object.

C++




#include <iostream>
using namespace std;
 
class MyExcept1 {};
 
class MyExcept2
{
public:
 
    // Conversion constructor
    MyExcept2 (const MyExcept1 &e )
    {
        cout << "Conversion constructor called";
    }
};
 
int main()
{
    try
    {
        MyExcept1 myexp1;
        throw myexp1;
    }
    catch(MyExcept2 e2)
    {
        cout << "Caught MyExcept2 " << endl;
    }
    catch(...)
    {
        cout << " Default catch block " << endl;
    }
    return 0;
}

Output:

Default catch block

As a side note, the derived type objects are converted to base type when a derived object is thrown and there is a catch block to catch base type. See this GFact for more details.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!