c++exception

C++ Exceptions - Is throwing c-string as an exception bad?


I am working on a small c++ program and learning exceptions. Is the following code "bad", and if so, what can I do to improve it?

try {
    // code
    if (some error) {
        throw "Description of error.";
    }
}
catch (char* errorMessage) {
    cerr << errorMessage << endl << "Fatal error";
}

Is there anything wrong with throwing a char array as an exception?

EDIT: Would this be a better way to go?

const char errorMessage[] = "Description of error";

try {
    // code
    if (some error) {
        throw errorMessage;
    }
}
catch (char* errorMessage) {
   cerr << errorMessage << endl << "Fatal error";
}

Solution

  • It is much better to throw a standard exception object. In general, the best practice is to throw something derived from std::exception so that if in some situation it does cause your program to terminate, the implementation has a better chance of printing a useful diagnostic.

    Because it isn't hard to do this, I would never recommend throwing a raw string literal.

    #include <stdexcept>
    
    void someFunction()
    {
        try {
            // code
            if (some error) {
                throw std::runtime_error( "Description of error." );
            }
        }
        catch (const std::exception& ex) {
            std::cerr << ex.what() << "\nFatal error" << std::endl;
        }
    }