If I want to throw an instance of a class, where should I alloc the exception object?


Should I use heap:

try{
throw new Exception("An error was found");
}
catch(Exception* e){
std::cout << e->get_message() << "\n";
delete except;
}


or should not use heap:

try{
throw Exception("An error was found");
}
catch(Exception& e){
std::cout << e.get_message() << "\n";
}

Recommended Answers

All 3 Replies

Throw the object and catch by reference or const reference. There's no need for dynamic allocation. Your second example is conventional.

Just to point out, that you shouldn't really throw an exception unless its absolutely necessary. Like the name suggest, an exception should be thrown in exceptional cases. If you can handle the exception then do it, else you have no choice but to propagate it.

Read this.

In the link you will find a good enough explanation why it is not good to throw pointers. My take on it is: What if the dynamic allocation fails and throws an exception of its own? Basically, in that case, you will never reach the actual throw statement, you might not catch the exception and then you will never know where your program actually failed. Throwing by value (temporary) and catching by reference is the way to go.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.