Customizing Error Messages in Custom Exception Types

How can I provide custom error messages when throwing my own exception types?

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.

Exception Types

Gain a thorough understanding of exception types, including how to throw and catch both standard library and custom exceptions in your code

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Handling Multiple Exception Types in a Single Catch Block
Is it possible to catch and handle multiple exception types in a single catch block?
Performance Impact of Exception Handling
Does using exception handling have a significant impact on program performance?
Best Practices for Exception Handling in C++
What are some best practices to follow when using exception handling in C++?
Understanding Exception Specifications in C++
What are exception specifications in C++ and when should they be used?
Handling Exceptions in Constructors
How should exceptions be handled when thrown from constructors in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant