Home  >  Article  >  Backend Development  >  How to Pinpoint the Origin of Unhandled Exceptions in C ?

How to Pinpoint the Origin of Unhandled Exceptions in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 17:48:03262browse

How to Pinpoint the Origin of Unhandled Exceptions in C  ?

Determining the Origin of Unhandled Exceptions

In exception handling, it is common to include line numbers and source file names to pinpoint the cause of an exception. When exceptions are generated manually, this information can be easily added. However, unhandled exceptions and those not explicitly thrown may present a challenge.

Using a Custom Exception Class with Macros

To overcome this limitation, a more robust solution is to employ a custom exception class and a macro. The following C code illustrates how it can be achieved:

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

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__);

Example Usage

With the custom exception class and macro in place, unhandled exceptions can be captured and their source pinpointed:

void f() {
    throw_line("Oh no!");
}

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

When this code is executed, the following error message is printed:

myFile.cpp:255: Oh no!

This clearly identifies the file and line number where the exception was thrown, providing valuable information for debugging and resolving the issue.

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

Statement:
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