Notes Exception & Templates
Notes Exception & Templates
catch(…)
Called as UNIVERSAL CATCH HANDLER which can handle any type of UNHANDLED
exception. Usually kept after all catch() handlers.
Example
Main()
{
try
{
throw 10;
throw ‘a’;
throw 2.5;
}
catch(int)
{
cout<<”exception caught”;
}
catch(…)
{
cout<<”all exceptions caught”;
}
}
Output:
Exception caught
All exceptions caught
All exceptions caught
Here throw 10; moves to catch(int) whereas for other throw statements respective catch() are
missing, so it calls catch(…) on remaining occasions.
Templates
Templates in C++ is an interesting feature that is used for generic programming and
templates in c++ is defined as a blueprint or formula for creating a generic class or a function.
Simply put, you can create a single function or single class to work with different data types
using templates.
Hence a class can create similar set of classes (family of classes)- generic classes
And a function can create a similar set of functions (family of functions)- generic functions
Function template
Class templates
public:
// Constructor of Test class.
Test(T n) : answer(n)
{
cout << "Inside constructor" << endl;
}
T getNumber()
{
return answer;
}
};
// Main function
int main()
{
// Creating an object with an integer type.
Test<int> numberInt(60);
return 0;
}
Output:
Inside constructor
Inside constructor
Integer Number is: 60
Double Number = 17.27
In this example generic data type T is replaced by int and double inputs to create multiple
copies of the class with T replaced by int and double respectively.