To provide custom error messages when throwing your own exception types, you can follow these steps:
Step 1: Add a constructor to your exception class that accepts a string parameter representing the error message:
#include <exception>
#include <string>
class CustomException : public std::exception {
public:
explicit CustomException(
const std::string& message)
: m_errorMessage(message) {}
// ...
};
Step 2: Store the error message in a member variable of your exception class:
class CustomException : public std::exception {
// ...
private:
std::string m_errorMessage;
};
Step 3: Override the what()
function to return the custom error message:
class CustomException : public std::exception {
public:
// ...
const char* what() const noexcept override {
return m_errorMessage.c_str();
}
// ...
};
Step 4: When throwing the exception, provide the custom error message as an argument:
throw CustomException("Something went wrong!");
Now, when you catch the exception, you can access the custom error message using the what()
function:
try {
// ...
} catch (const CustomException& e) {
std::cout << "Error: " << e.what();
}
This way, you can provide informative and specific error messages when throwing your custom exception types.
Answers to questions are automatically generated and may not have been reviewed.
Gain a thorough understanding of exception types, including how to throw and catch both standard library and custom exceptions in your code
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course