Search code examples
c++exceptiontry-catchbacktracking

How is it possible to overload the throw function while writing a custom exception class in C++?


I wrote a routine to store the backtrace and line no and file name etcetera. The purpose for this was to store such data for whenever an exception is thrown. However, the problem I am facing is that my routine will be called from the catch block and it will end up storing the backtrace up to the catch block. This is not good. I only must add the backtrace till the place where the exception is thrown. I cannot (obviously call it inside the try block since in that case I will end up storing a backtrace even in the cases where no exception is thrown). I could also always store the backtrace to the end of the try block and access it inside the catch block; but there is no way of knowing at which line of the try block the exception will be thrown. Thus the throw function seems to be a good place to add the routine call. But I dont know how to do it. Please help me.

If my strategy seems inherently wrong, please feel free to point me a better solution. If the problem itself is not clear, please leave a comment.

P.S. I wrote the custom exception class to inherit from std::runtime_error.


Solution

  • There is no 'throw function' defined by C++ that you can override. Throwing is handled by the C++ implementation and there's no standard way to insert any kind of code for every throw.

    Instead what you can do is make your exception type store the current backtrace when it is constructed.

    std::string get_backtrace() {
        return "this is the backtrace...";
    }
    
    struct backtrace_exception : public std::exception {
        std::string b;
    
        backtrace_exception() : b(get_backtrace()) {}
    };
    
    int main() {
        try {
            throw backtrace_exception();
        } catch(backtrace_exception &e) {
            std::cout << e.b;
        }
    }