Yup - that's the way to go. To define your own type of exceptions to handle custom exception events, you should always derive from the stl::exception. But since you're inheriting the class, and not implementing any kind of interface, you don't really need to redefine any of the method bodies in superclass exception.
What you should include though, is a default message, that can be printed out of this class + the ability to pass and store a custom error message to this class.
Let me give you an example ( I might not be correct with the syntax - am coverting an idea I got from one of my Java courses into C++)
CODE
using namespace std;
....
.......
class interpreter_exception : public stl::exception
{
private:
// Var to hold error message
string message;
public:
// Constructor
interpreter_exception ( string m )
{
// If no message was passed to the constructor, use the default message
if ( m.length == 0 )
{
message = "Interpreter Exception Detected.";
}
else
{
message = m;
} // end if-else
}; // end constructor
// Method to print out the error message
public void Message ()
{
cout << message;
}; // end Message
}; // end interpreter_exception class
// This is main program body where you throw the exception
try
{
// Do Something (In Java you can use the "new" keyword to call the constructor
// and pass a custom message to the exception class. I'm kinda confused,
// in C++ you probably don't need to use the "new" - or maybe optionally used.
throw new interpreter_exception ( "Some error occured" );
// OR
throw interpreter_exception;
}
catch( interpreter_exception e )
{
// Print out the error message
e.Message();
} // end try-catch
Hope this will guide you to creating custom exception handlers in future... the concept is extremely easy, although I'd be able to illustrate it better with Java.
P.S. What you've shown, would do too - except that it won't show the message "interpreter exception detected" or whatever message you pass it to. It will try print out some standard error message that the exception class has.
Reply