Exception Types

Customizing Error Messages in Custom Exception Types

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Exception Types

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Exception Types

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved