首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何构建一个异常类来报告C++中的哪些文件和行号?

在C++中,可以通过构建一个异常类来报告文件和行号。以下是一个示例的异常类的构建方式:

代码语言:txt
复制
#include <exception>
#include <string>

class FileLineException : public std::exception {
public:
    FileLineException(const std::string& file, int line) : file_(file), line_(line) {}

    const char* what() const noexcept override {
        return message_.c_str();
    }

    const std::string& getFile() const {
        return file_;
    }

    int getLine() const {
        return line_;
    }

private:
    std::string file_;
    int line_;
    std::string message_ = "Exception occurred at file: " + file_ + ", line: " + std::to_string(line_);
};

在上述代码中,我们定义了一个名为FileLineException的异常类,继承自std::exception。该异常类接受两个参数:文件名和行号,并将其保存在私有成员变量file_line_中。

异常类中重写了what()函数,该函数返回一个const char*类型的异常信息。在这个例子中,异常信息包含了文件名和行号。

此外,我们还提供了两个公有成员函数getFile()getLine(),用于获取异常发生的文件名和行号。

使用该异常类的示例如下:

代码语言:txt
复制
void foo() {
    throw FileLineException(__FILE__, __LINE__);
}

int main() {
    try {
        foo();
    } catch (const FileLineException& e) {
        std::cout << "Exception caught at file: " << e.getFile() << ", line: " << e.getLine() << std::endl;
    }

    return 0;
}

在上述代码中,我们在foo()函数中抛出了一个FileLineException异常,并传入__FILE____LINE__宏作为参数。在main()函数中,我们使用try-catch块捕获并处理该异常,打印出异常发生的文件名和行号。

这样,通过构建一个异常类,我们可以在C++中报告异常发生的文件和行号,方便调试和定位问题。

腾讯云相关产品和产品介绍链接地址:

请注意,以上链接仅供参考,具体产品选择应根据实际需求进行评估和决策。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券