C++异常处理


#include <exception>
class xcp_exception : public std::exception
{
public:


xcp_exception(std::string err = ""): m_err(err)
{
}


    virtual ~xcp_exception() throw()
{

}


    virtual const char* what() const throw()
{
printf("xcp_exception: %s\n", m_err.c_str());
return m_err.c_str();
}

private:
std::string m_err;
};






int test_execption() 
{
int nRet = 0;

printf("it is test1.\n");

xcp_exception ee("It is test.");
throw ee;

printf("it is test2.\n");

return nRet;
}




int main(int argc, char * argv[])
{
int nRet = 0;


try
{
nRet = test_execption();
printf("ret of test_execption: %d", nRet);
}
catch (xcp_exception err)
{
printf("catch xcp_exception err\n");
err.what();
}
catch (xcp_exception &err)
{
printf("xcp_exception &err\n");
err.what();
}
catch (std::exception err)
{
printf("std::exception err\n");
err.what();
}
catch (...)
{
printf("catch others exception.\n");
}


printf("complete to main()\n");

return 0;
}




关键事项:
(1)函数使用throw进行异常声明(指明只有这些异常产生了才抛出), 也可以不修饰(只要函数内部有异常就抛出)
(2)如果一项catch 匹配成功了, 后面的catch 就不会再执行了,除非你再catch中再调用 throw; 重新抛该异常到下面catch检查。
(3)catch后面的语句还会继续执行。
(3)如果抛异常没有catch到,系统会 Aborted
(4)每个try块至少跟一个catch,否则系统调用terminate()函数终止程序
(5)抛 xcp_exception 异常, catch 该类型对象 和 该类型引用 效果是一样的。


catch (xcp_exception err)
{
printf("catch xcp_exception err\n");
err.what();
}
catch (xcp_exception &err)
{
printf("xcp_exception &err\n");
err.what();
}




(6)
可以在函数的声明中列出这个函数可能抛掷的所有异常类型。
例如:void fun() throw(A,B,C,D);


若无异常接口声明,则此函数可以抛掷任何类型的异常。


不抛掷任何类型异常的函数声明如下:
void fun() throw();




(7)c++标准中有个异常基类, 写自定义异常可以继承它。 也可以不继承它完全独立的类。
  class exception 
  {
  public:
    exception() throw() { }
    virtual ~exception() throw();
    /** Returns a C-style character string describing the general cause
     *  of the current error.  */
    virtual const char* what() const throw();
  };



(8)为了防止异常没有捕获到造成程序 terminate
在catch块最后加上 catch (...) 捕获所有异常


(9)如果异常类型存在父子继承关系, 抛异常子类型对象,catch异常父类型也能捕获到。


(10) 函数内部throw 后, 函数直接退出, 函数内部throw后面的代码不会再执行


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值