服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++异常重抛出实例分析

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

2021-09-03 15:00川尘 C/C++

在本文里小编给大家分享的是关于C++异常重抛出实例分析,有兴趣点朋友们可以跟着学习下。

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

?
1
2
3
4
5
6
try {
  //Execute some code   
} catch (Exception& e) {
  //Peform some operations before exits
  throw;
}

语句throw重新抛出了异常。

看一个实际的例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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++异常重抛出实例分析

知识点扩展

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

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

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

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

?
1
2
3
4
5
6
7
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
}

以上就是C++异常重抛出实例分析的详细内容,更多关于C++异常重抛出的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/bwjblogs/p/12826726.html

延伸 · 阅读

精彩推荐