C++异常重抛出 C++异常重抛出实例分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++异常重抛出 C++异常重抛出实例分析

川尘   2021-04-22 我要评论

如果我们编写了一个函数,函数内部可能会出现异常,但是我们不想在这个函数内处理,而是想要通知调用者,那么C++允许它重抛出这个异常。语法如下:

try {
  //Execute some code    
} catch (Exception& e) {
  //Peform some operations before exits
  throw;
}

语句throw重新抛出了异常。

看一个实际的例子:

#include <iostream>
#include <stdexcept>

using namespace std;

int f(){
  try{
    throw runtime_error("Exception in f");
  } catch(exception& e){
    cout << "Exception caught in f" << endl;
    cout << e.what() << endl;
    throw;
  }
}
int main()
{
  try{
    f();
  } catch(exception& e){
    cout << "Exception caught in main" << endl;
    cout << e.what() << endl;
  }
  return 0;
}

运行结果:

知识点扩展

c++重新抛出异常
有可能单个catch不能完全处理一个异常,此时在进行了一些处理工作之后,需要将异常重新抛出,由函数调用链中更上层的函数来处理。重新抛出由“throw;”语句实现,throw后不跟表达式或类型。

“throw;”将重新抛出异常对象,它只能出现在catch或catch调用的函数中,如果出现在其它地方,会导致调用terminate函数。

被重新抛出的异常是原来的异常对象,不是catch形参。该异常类型取决于异常对象的动态类型,而不是catch形参的静态类型。比如来自基类类型形参catch的重新抛出,可能实际抛出的是一个派生类对象。

只有当异常说明符是引用时,在catch中对形参的改变,才会传播到重新抛出的异常对象中。

catch (my_error & eObj) {  
 eObj.status = severeErr; 
 throw; // the status member of the exception object is severeErr
} catch (other_error eObj) {
 eObj.status = badErr;
 throw; // the status member of the exception rethrown is unchanged
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们