0

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";
}

4
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by mike_2000_17
0

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

0

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.

2

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.