I heard you should never throw a string because there is a lack of information and you\'ll catch exceptions you dont expect to catch. What are good practice for throwing exc
Throwing pointers is probably not a good thing, as it complicates ownership of the thrown object. Class type exceptions are probably better than fundamentals simply because they can contain more information about the reason for the exception.
In using a class or class hierarchy there are a couple of points you should consider:
Both the copy constructor and destructor of the exception object must never throw an exception. If they do you're program will terminate immediately.(ISO 15.5/1)
If your exception objects have base
classes, then use public inheritance.
A handler will only be selected for a
derived to base class if the base
class is accessible.(ISO 15.3/3)
Finally, (for all exception types) ensure that the expression being thrown cannot itself result in an exception being thrown.
For example:
class Ex {
public:
Ex(int i)
: m_i (i)
{
if (i > 10) {
throw "Exception value out of range";
}
}
int m_i;
};
void foo (bool b) {
if (! b) {
// 'b' is false this is bad - throw an exception
throw Ex(20); // Ooops - throw's a string, not an Ex
}
}