首頁 > 後端開發 > C++ > 主體

如何查明未處理異常的確切來源?

Mary-Kate Olsen
發布: 2024-11-14 11:30:02
原創
339 人瀏覽過

How to Pinpoint the Exact Source of Unhandled Exceptions?

Identifying the Exact Source of Unhandled Exceptions

It is often desirable to determine the specific line of code that caused an exception, even if it was not explicitly generated by the programmer.

Custom Exception Class and Macro

A recommended approach involves creating a custom exception class and a corresponding macro. For example:

class my_exception : public std::runtime_error {
    std::string msg;
public:
    my_exception(const std::string &arg, const char *file, int line) :
    std::runtime_error(arg) {
        std::ostringstream o;
        o << file << ":" << line << ": " << arg;
        msg = o.str();
    }
    ~my_exception() throw() {}
    const char *what() const throw() {
        return msg.c_str();
    }
};
#define throw_line(arg) throw my_exception(arg, __FILE__, __LINE__);
登入後複製

Usage:

The my_exception class constructs customized exception messages that include the file name, line number, and user-defined error message. The throw_line macro is used to generate custom exceptions with these enhanced error messages.

In the following example, the throw_line macro is used within function f:

void f() {
    throw_line("Oh no!");
}
登入後複製

When f throws the exception, the main function catches it and prints the customized error message to the console:

int main() {
    try {
        f();
    }
    catch (const std::runtime_error &ex) {
        std::cout << ex.what() << std::endl;
    }
}
登入後複製

This approach provides a convenient mechanism for generating exceptions with detailed information about their origin, regardless of whether they were generated explicitly or not.

以上是如何查明未處理異常的確切來源?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板