c++异常 连续抛出异常

 

今天天遇到这样一个问题,连续两次抛出异常,但是只有一个catch,会导致core这个时候会导致core,

单线程编程中可能很少遇到这样的问题,但是多线程中是很容易遇到的,

举个例子:catch代码在主线程M中,子线程C1抛出异常,如果引起子线程C2的终止,在C2终止的过程中也产生异常,那就出问题了。

下面贴一个测试案例

#include <iostream>
#include <string>
#include <boost/shared_ptr.hpp>
#include <exception>
class Exception
{
        public:
                Exception(const std::string& msg)
                        :_message(msg)
                {
                }
                const std::string& what()
                {
                        return _message ;
                }
        private:
                std::string _message ;
};
class B {
        public:
                B()
                {
                        _ch = new char('h') ;
                        std::cout << "B()" << std::endl;
                }
                ~B()
                {
                        delete _ch ;
                        std::cout << "~B()" << std::endl;
                }
                void visit()
                {
                        std::cout << *_ch << ",first" << std::endl;
                        throw Exception("Exception - huangxiaowei");
                        std::cout << *_ch << ",second" << std::endl;
                }
        public:
                char* _ch ;
};

class A {
        public:
                B b;
        public:
                A():
                        b()
                {
                        std::cout << "A()" << std::endl;
                }
                ~A()
                {
                        std::cout << "~A()" << std::endl;
                        b.visit();
                }
                void get()
                {
                        b.visit();
                }

};

int main() {
        try
        {
                //boost::shared_ptr<A> spa(new A());
                //spa->get();
                A a ;
                a.get();
        }
        catch(Exception& e)
        {
                std::cout << e.what() << std::endl;
        }
}


这是一个很巧妙的例子

调用get的时候 B方法visit抛出异常,这个时候A要析构,又一次调用B的visit再次抛出异常,

导致程序core掉

这其中的原理没有深入研究

原文地址:https://www.cnblogs.com/james1207/p/3366079.html