Bagaimana untuk Menentukan Sumber Tepat Pengecualian Tidak Terkendali?

Mary-Kate Olsen
Lepaskan: 2024-11-14 11:30:02
asal
339 orang telah melayarinya

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__);
Salin selepas log masuk

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!");
}
Salin selepas log masuk

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;
    }
}
Salin selepas log masuk

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

Atas ialah kandungan terperinci Bagaimana untuk Menentukan Sumber Tepat Pengecualian Tidak Terkendali?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan