Throwing a string is really a bad idea.
In your code you are throwing a const char*
. Throwing a built-in type (like an int
, or float
, or a const char*
like in this case) is a bad idea because these built-in types don't carry proper contextual error information. In fact, when an exception is caught, it's important to understand the reason for the exception to take proper action. But a built-in type doesn't properly provide such information, making it difficult at the catch-site to understand the reason and the cause for the exception.
Moreover, throwing a built-in type is also confusing, as it's not idiomatic modern C++. The idiomatic C++ way of throwing an exception is to define a proper C++ class to represent the exception, typically deriving it from std::exception
, or from some other class derived from std::exception
, and then throw
an instance of such exception class.
You could also simply throw some of the C++ exception classes already defined in the C++ Standard Library, like std::runtime_error
.
For example, you could throw a std::runtime_error
, passing an error message string to the constructor, like this:
throw std::runtime_error("Your error message");
and, at the catch site, you can catch the runtime_error
exception by const reference (const &
), and invoke the what()
method to get the error string.
try {
...
} catch (const std::runtime_error& ex) {
// Invoke ex.what() to get the error message
}
But do not throw the "naked" string.
In case you want to define a custom exception class, you can derive it for example from std::runtime_error
like this:
class YourCustomException
: public std::runtime_error
{
public:
YourCustomException(const char* message)
: std::runtime_error(message) {
}
YourCustomException(const std::string& message)
: std::runtime_error(message) {
}
};
throw it like this:
throw YourCustomException("Your error message");
and catch it like this:
try {
...
} catch (const YourCustomException& ex) {
// Invoke ex.what() to get the error message
}