This is the code:
#include <iostream>
#include <exception>
using namespace std;
class excp1:exception
{
public:
virtual const char* what() const throw()
{
return "Bad ass exception";
}
};
int main(int argc, char **argv)
{
try
{
if(1!=0)
throw new excp1();
}
catch(excp1& e)
{
cerr<<e.what();
}
return 0;
}
But it doesn’t print what I have put as return value of what (“Bad ass exception”), instead it prints:
Terminate called after throwing an instance of' excp1*'
Aborted
How to manage to print what I want?
You should throw the exception by value and catch it by reference.
You should have:
Throwing a pointer type with dynamic memory allocation would leak the memory and cause undefined behavior.