C++异常处理

C++中异常处理:

1. 对异常的处理可以分为:异常检测与处理二个阶段。

  能过try{}与catch(ecxptionclass &e){}来解决。

int main(int argc, char *argv[])
{
    try
    {
        excptionclass expOne;
        //excptionclass expOne;
        throw expOne;

    }
    catch (excptionclass e)
    {

        printf(" catch (...)here \n");
        
    }
    
    return 0;
}

结果为:

1 excptionclass() is called
2 copy excptionclass() is called
3 copy excptionclass() is called
4 ~~~~excptionclass() is called
5  catch (...)here
6 ~~~~excptionclass() is called
7 ~~~~excptionclass() is called
8 Press any key to continue

可以分析,在throw 一个对象时,它copy一个副量,再传给catch中,当catch到时,因为

excptionclass e 可知,又会调用一次copy construct函数。
注:当catch(excptionclass &n
)时,那么会不同。

2. 导常对象继承问题及指针
当是静态与动态问题2.当是指针时,那么要小心当处理异常时的栈展开问题。
3.栈展开
(1).当处理异常时,在函数中已经建立的局部对象会调用析构函数。
(2).析构函数应该不抛出异常,如果真有那么会调用terminate函数。
(3).当在对像的构造函数时,抛出异常,也要保证可以释放
(4).当未有处理异常的catch时,那会调用terminate函数
4. catch exception
(1)匹配处理 可以允许的转换:非const 到const 的转换;派生类到基类转换;数组转换为数组类型指针,函数转换为函数指针.
(2)异常说明符,可以是对像,也可以是引用
(3)继承关系,当为引用时,可以运用动态性。
(4)必须反映层次,多个catch子句时,必须从最低派生类型到最高派生类型排序。

   5 重新抛出

  try

  {}

  catch(exceptionclass &e)

  {

  ......

  throw;

  }

注:重新抛出的异常,对异常的修改性,要看catch()说明符是对像还是引用。

int main(int argc, char *argv[])
{
   try
   {
       try
    {
        excptionclass expOne;
        //excptionclass expOne;
        throw expOne;

    }
    catch (excptionclass &e)
    {
        e.a=10;
        printf(" catch(excptionclass e) is called here \n");
        throw;
        
    }
    
   }
   catch(excptionclass &e)
    {
        printf(" catch (...)here \nthe i is %d\n",e.a);
    }
    
    
    return 0;
}
excptionclass() is called
copy excptionclass() is called
~~~~excptionclass() is called
 catch(excptionclass e) is called here
 catch (...)here
the i is 10
~~~~excptionclass() is called
Press any key to continue

  就明白了。

关于异常类的层次,大致分为runtime_error 和 logic_error二个方面。

6。关于aut_ptr为了使new class(); 与delete p;之间发生异常时,对于内存的回收工作,有一些特性,比如:复制与赋值的破坏性,不能共存性及不能初始一个new array[n]等缺点。

7。对定义异常的说明

void fun() throw()

{}

表示此函数不会抛出异常。如果真的抛出了,会调用unexpected函数,退出,这样字义,有利于,在函数不会抛出异常时,可以执行被可能抛出异常的代码所抑制的优化问题。

关于异常说明与虚函数问题:

那么子函数throw(。。。)的异常必然为base类中,相对虚函数的子类。。

8 函数指針问题;

源指针的异常说明必须至少与目标执政一样严格!!!

posted @ 2013-04-29 20:23  程序world  阅读(102)  评论(0)    收藏  举报