Custom exception messages can enhance error handling by providing detailed and context-specific information when exceptions are thrown. This is achieved by creating custom exception classes that inherit from the standard std::exception class and override its what() method to return informative error messages.
A custom exception class allows you to define specific types of errors in your application with custom messages and additional context. This helps differentiate between different error scenarios and provide detailed information about what went wrong.
std::exception: Your custom exception class should derive from std::exception or a subclass like std::runtime_error. This ensures your custom exception is compatible with C++’s exception-handling mechanism.what() method: The what() method is inherited from std::exception and returns a C-style string (const char*). In your custom class, you can override it to return the error message.#include <iostream>
#include <exception>
#include <string>
// Custom exception class inheriting from std::exception
class MyCustomException : public std::exception {
private:
std::string message;
public:
// Constructor to set the error message
MyCustomException(const std::string& msg) : message(msg) {}
// Override the what() method to return the custom error message
virtual const char* what() const noexcept {
return message.c_str();
}
};
int main() {
try {
// Throwing a custom exception with a detailed message
throw MyCustomException("An error occurred: invalid input provided.");
} catch (const MyCustomException& e) {
// Catching and printing the custom exception's message
std::cerr << "Caught custom exception: " << e.what() << std::endl;
}
return 0;
}
what() method returns this message.FileNotFoundException, InvalidUserInputException), each with its own message.class FileNotFoundException : public std::exception {
public:
const char* what() const noexcept override {
return "File not found error.";
}
};
class InvalidUserInputException : public std::exception {
public:
const char* what() const noexcept override {
return "Invalid user input error.";
}
};
int main() {
try {
throw FileNotFoundException();
} catch (const std::exception& e) {
std::cerr << "Caught: " << e.what() << std::endl;
}
try {
throw InvalidUserInputException();
} catch (const std::exception& e) {
std::cerr << "Caught: " << e.what() << std::endl;
}
}
std::exception.what() method returns these messages, improving the clarity and usefulness of exceptions in error handling.