I’ve created the class Someting which throws an exception SomethingException (SomethingException inherits from std::exception) when it fails to instantiate. the problem is I can’t catch SomethingException as such (I had to do a dirty trick to catch it).
There is somewhere in the program where it executes:
This doesn’t work, the exception is not caught and the program crashes.
try{
Something* s = new Something();
}
catch (SomethingException* e){
std::cerr<<e.what();
}
In contrast this does work (exception is caught and the correct message shown) but I really have the feelin I shouldn’t be doing this
try{
Something* s = new Something();
}
catch (std::exception* e){
SomethingException* e2 = (SomethingException*) e;
std::cerr<<e.what();
}
Because the pointer is casted I can only make this work if and only if one type of exception is thrown. The moment I need to catch various types this won’t work.
Is there a way to caught a custom exception in a more correct way?
Edit:
The exception is thrown as follows
//...
throw new SomethingException ("Errormessage"); //Custom exception constructor
//...
The declaration of Something::Something() is
Something::Something() throw(...)
Using the declaration
Something::Something() throw(SomethingException)
//or
Something::Something() throw(SomethingException*)
Throws a lot of warnings (Warning C4290)
In general it’s best to throw exceptions by value and catch them by reference:
You would only be able to catch an exception with
catch (SomethingException*)if you were to throw it withthrow new SomethingException(). There isn’t enough information in your question to tell, but the problem may be in howSomethingExceptionderives fromstd::exception. Verify that or change it to inherit from, say,std::runtime_errororstd::logic_errorinstead.Also, don’t use
throwspecifiers. Just don’t. No compiler affords any benefit to using checked exceptions: in effect, checked exceptions aren’t checked except to fail horribly (throwingstd::bad_exception) in the event of an exception that doesn’t conform to the specifier. That’s probably what’s happening in your code.