Home > Backend Development > C++ > How to Pinpoint the Exact Source of Unhandled Exceptions?

How to Pinpoint the Exact Source of Unhandled Exceptions?

Mary-Kate Olsen
Release: 2024-11-14 11:30:02
Original
402 people have browsed it

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__);
Copy after login

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!");
}
Copy after login

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 &amp;ex) {
        std::cout << ex.what() << std::endl;
    }
}
Copy after login

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

The above is the detailed content of How to Pinpoint the Exact Source of Unhandled Exceptions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template