Coupon Accepted Successfully!


Class Templates With Exception Handling

The following program illustrates how excepting handling can be implemented with class templates:

19.12 Write a program to show exception handling with class template.



class sq {};

template <class T>

class square


T s;


square ( T x)


sizeof(x)==1 ? throw sq() : s=x*x;


void show()


cout<<“\n Square:”<<s;



void main()




square <int> i(2);


square <char> c(‘C’);



catch (sq)


cout<<“\n Square of character cannot be calculated”;




Square: 4

Square of character cannot be calculated

Explanation: In the above program, the class square uses the template type of argument. Using conditional operators, the size of the passed argument is checked. If it is equal to one, an exception is thrown; otherwise, the square is calculated and stored in the class data member s. The show() function displays the square on the screen. When character-type data are entered, an exception is thrown, because the size of the character is one and the square cannot be calculated.

Test Your Skills Now!
Take a Quiz now
Reviewer Name