In C++, The exception specification is part of function signature and it tells which type of exceptions the function is allowed to throw.
void myfunc() throw(double) //Specification is double
{
throw 5.2; //Throws double
}
The above function is allowed to throw only exception of double type.
If this function tries to throw any other type, then the program will terminate.
Example,
void myfunc() throw(double) //Specification is double
{
throw 5; //Throws int type
}
Output:
Functions to throw multiple types of exceptions
If the function wants to throw multiple types of exception, then the specification may look like as in below code. The function myfunc can throw an int or a double or a std::string.
#include <iostream> //main header
using namespace std; //for namespace
void myfunc(int avar) throw(double, int, std::string)
{
if(avar == 1)
throw 5;
else if(avar == 2)
throw 5.3;
throw "random excption";
}
int main()
{
try
{
myfunc(2);
}
catch(...) //catch anytype
{
cout << "Catch()" << endl;
}
return 0;
}
In above code, the catch block is capable of catching all types of exceptions therefore, it shall print following output
Catch()
Function not throwing any exception
In this case, specification will have no types in the brackets, the program will terminate if the function now tries to throw any exception. Even if there are catch blocks available, then also the execution will abort.
#include <iostream> //main header
using namespace std; //for namespace
void myfunc() throw() //shall not throw anything
{
throw 5; //still throwing an int
}
int main()
{
try
{
myfunc();
}
catch(...)
{
cout << "Catch()" << endl;
}
return 0;
}
The output is:
In C++11, there is a new keyword ‘noexcept’ to denote the scenario that function will not throw exception
void myfunc() noexcept
{
throw 5; //Still throwing an exception
}
In such case, the compiler will generate warning
Any type Specification to indicate that function which can throw any type of exception
In this case, there will be nothing written after the function brackets
void myfunc() //This function may throw or may not throw
{
throw 5;
}