Fixing Custom Exception Constructor Error

保存时间:2026/4/4 18:00:14

Prompt

Response

You're absolutely right! The std::runtime_error constructor only takes a single std::string argument for the error message. Your THROWGEMERROR macro attempts to pass additional information (__FILE__, __LINE__, __PRETTY_FUNCTION__) directly to the GEMError constructor, which then tries to pass those to the base class constructor, leading to the error.

To fix this, you'll need to modify the GEMError constructor to accept the additional information and then format it into a single string that you pass to the std::runtime_error constructor. Here's the corrected code:

C++
#include <stdexcept>
#include <string>
#include <sstream>

class GEMError : public std::runtime_error {
public:
  GEMError(const std::string &message, const char* file, int line, const char* function)
      : std::runtime_error(constructMessage(message, file, line, function)) {}

private:
  static std::string constructMessage(const std::string &message, const char* file, int line, const char* function) {
    std::stringstream ss;
    ss << message << " in " << function << " at " << file << ":" << line;
    return ss.str();
  }
};

// Macro for throwing GEMError exceptions with source code information
#define THROWGEMERROR(message) \
throw GEMError(message, __FILE__, __LINE__, __PRETTY_FUNCTION__);

class SGFError : public std::runtime_error {
public:
  SGFError(const std::string &message) : std::runtime_error(message) {}
};

Here's a breakdown of the changes:

  1. Modified GEMError Constructor:

    • The constructor now takes four arguments: the error message (as a const std::string&), the file name (const char*), the line number (int), and the function name (const char*).

    • Instead of directly passing these to the base class, it now calls a private static helper function constructMessage.

    • The result of constructMessage (a formatted std::string) is then passed to the std::runtime_error constructor.

  2. Private Static Helper Function constructMessage:

    • This function takes the error message, file, line, and function as input.

    • It uses an std::stringstream to build a more informative error message by concatenating all the provided information.

    • Finally, it returns the formatted string.

Now, when you use the THROWGEMERROR macro, the file, line number, and function name will be captured and included in the error message of the GEMError exception. When you catch and examine the exception's what() method, you'll get a more detailed context for the error.