How can some code be run each time an exception is thrown in a Visual C++ program?

前端 未结 6 714
清歌不尽
清歌不尽 2020-12-18 08:16

If an exception is thrown in a C++ program control is either transferred to the exception handler or terminate() is called.

Even if the program emits so

6条回答
  •  猫巷女王i
    2020-12-18 08:56

    When the language doesn't support it, and you can't live without it, hack... :-/

    #include 
    #include 
    
    namespace Throw_From
    {
        struct Line
        {
            Line& set(int x) { x_ = x; return *this; }
            int x_;
    
            template 
            void operator=(const T& t) const
            {                                                                       
                throw t;
            }                                                                       
        };                                                                          
        Line line;                                                                  
    }                                                                               
    
    #define throw Throw_From::line.set(__LINE__) =                                  
    
    void fn2()                                                                      
    {                                                                               
        throw std::runtime_error("abc");                                            
    }                                                                               
    
    void fn1()                                                                      
    {                                                                               
        fn2();                                                                      
    }                                                                               
    
    int main()                                                                      
    {                                                                               
        try
        {
            fn1();
        }
        catch (const std::runtime_error& x)
        {
            std::cout << Throw_From::line.x_ << '\n';
        }
    }
    

提交回复
热议问题