• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

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掉

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

 

 

 

posted @ 2013-10-12 22:26  Class Xman  阅读(445)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3