C++ add value to exception message
To add a value to an exception message in C++, you can use the what()
function provided by the exception
class. Here are the steps to do so:
- Create a custom exception class: Start by creating a custom exception class that inherits from the
std::exception
class. For example:
class MyException : public std::exception {
public:
MyException(const std::string& message, int value) : message_(message), value_(value) {}
const char* what() const noexcept override {
std::string fullMessage = message_ + " (Value: " + std::to_string(value_) + ")";
return fullMessage.c_str();
}
private:
std::string message_;
int value_;
};
Override the
what()
function: In the custom exception class, override thewhat()
function provided by thestd::exception
class. Within this function, create a string that combines the original exception message with the additional value. In this example, we use themessage_
andvalue_
member variables to store the original message and value, respectively. We then create afullMessage
string that concatenates these values together.Use the custom exception: Once the custom exception class is defined, you can use it in your code to throw exceptions with additional value information. For example:
void myFunction() {
int value = 42;
try {
if (value < 0) {
throw MyException("Value is negative", value);
}
// Rest of the code
} catch (const std::exception& e) {
std::cout << "Exception: " << e.what() << std::endl;
}
}
In this example, the myFunction()
function checks if the value
is negative. If it is, it throws a MyException
with the message "Value is negative" and the corresponding value
as an additional piece of information. The catch
block then catches the exception and prints the exception message using e.what()
, which includes the additional value information.
That's it! By following these steps, you can add a value to an exception message in C++.